如何解决Django管理员:从另一侧添加外键对象
所以我有这两个模型
class Recipe(models.Model):
short_description = HTMLField(max_length=400)
likes = models.ManyToManyField(User,blank=True,related_name='recipe_likes')
slug = models.SlugField(blank=True,unique=True)
published_date = models.DateTimeField(blank=True,default=datetime.now)
ratings = GenericRelation(Rating,related_query_name='recipes')
class Ingredient(models.Model):
name = models.CharField(max_length=20)
amount = models.FloatField()
recipe = models.ForeignKey(Recipe,on_delete=models.CASCADE,related_name='recipe_ingredients')
在“食谱”部分的管理面板中,如果我选择一个食谱,希望能够为该食谱添加成分,我需要什么?我想我不知道使用正确的搜索词,希望您理解我的意思。
感谢您的帮助。
编辑 这是解决方案:
from django.contrib import admin
from .models import Recipe,Ingredient
class IngredientInline(admin.TabularInline):
model = Ingredient
extra = 3
@admin.register(Recipe)
class RecipeAdmin(admin.ModelAdmin):
list_display = ('title',)
search_fields = ('title',)
inlines = [IngredientInline,]
解决方法
您需要阅读InlineModelAdmin
上的内容:
https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#inlinemodeladmin-objects
当您通过模型管理类注册模型时,添加一个inlines
列表。
文档对此很有帮助,因此,如果您有更详细的问题,请扩展您的问题!
,from django.contrib import admin
from .models import Recipe,Ingredient
class IngredientInline(admin.TabularInline):
model = Ingredient
extra = 3
@admin.register(Recipe)
class RecipeAdmin(admin.ModelAdmin):
list_display = ('title',)
search_fields = ('title',)
inlines = [IngredientInline,]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。