首页 > 解决方案 > Django admin:从另一端为外键添加对象

问题描述

所以我有这两个模型

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,]

标签: pythondjangodjango-modelsdjango-admin

解决方案


您需要阅读InlineModelAdmins:

https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#inlinemodeladmin-objects

当您向模型管理类注册模型时,请添加一个inlines列表。

文档很好,所以如果您有更详细的问题,请扩展您的问题!


推荐阅读