python - 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,]
解决方案
您需要阅读InlineModelAdmin
s:
https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#inlinemodeladmin-objects
当您向模型管理类注册模型时,请添加一个inlines
列表。
文档很好,所以如果您有更详细的问题,请扩展您的问题!
推荐阅读
- kotlin - 使用 Kotlin 属性覆盖 JVM 方法
- html - 跨多个子目录使用 HTML 模板
- android - 如何确保正确执行按钮功能
- java - Java i/o 程序错误 throwFor(Unknown Source)
- python - 我想在输入用户时显示一些有价值的信息
- python - Heroku 上的 Plotly Dash 服务器推送失败 - bonjour-py==0.3
- java - 映射转换器的 Json 字符串,
- logic - 好食物不便宜是否意味着便宜的食物不好?
- android - 图像裁剪权限后的 onSuccessListner
- gcc - mingw64 的 gcc 不使用 mingw 套件的汇编程序