如何在Django管理员更改表单中显示相关表的内容?

时间:2018-05-04 05:08:32

标签: python django django-models django-admin

我是编程,Python和Django的新手,所以请耐心等待。我一直在Django写一个练习应用程序来存储烹饪食谱。我有两个模型:

class Recipe(models.Model):
    recipe_name = models.CharField(max_length=30)
    recipe_instructions = models.TextField()
    recipe_whyitworks = models.TextField(verbose_name="Why It Works")
    recipe_date = models.DateField()
    def __str__(self):
       return self.recipe_name
    def was_published_recently(self):
       return self.recipe_date >= timezone.now() -datetime.timedelta(days=5)

class Ingredient(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    ingredient_name = models.CharField(max_length=30)
    ingredient_qty = models.DecimalField(verbose_name='Quantity', max_digits=3, decimal_places=2)
    ingredient_uom = models.CharField(verbose_name='Unit of Measure', max_length=15)
    def __str__(self):
        return self.ingredient_name

我有管理员设置,可以编辑任何一个表:

from django.contrib import admin

# Register your models here.
from .models import Recipe, Ingredient

admin.site.register(Recipe)
admin.site.register(Ingredient)

我想要做的是当我点击“成分”时,我希望它显示添加到配方中的所有先前成分,以及表格中每个的数量和度量单位,以及字段这允许我添加一个新的。在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您可以添加以下内联:

<强> admin.py

from django.contrib import admin

class IngredientInline(admin.TabularInline):
    model = Ingredient

class RecipeAdmin(admin.ModelAdmin):
    inlines = [
        IngredientInline,
    ]

admin.site.register(Recipe, RecipeAdmin)
admin.site.register(Ingredient)