【问题标题】:How can I edit the values in a intermediate ManyToMany table from the Django Admin site?如何从 Django 管理站点编辑中间多对多表中的值?
【发布时间】:2018-10-02 06:12:14
【问题描述】:

我希望能够通过 Django 管理站点在我的数据库中创建鸡尾酒。为此,我有一个“鸡尾酒”模型和一个“成分”模型。他们需要一个允许附加字段“amount_in_oz”的多对多关系,因此我使用带有“through”的“IngredientAmount”中间模型。在管理站点中,当我单击“添加鸡尾酒”时,我希望能够命名鸡尾酒,然后从“成分”模型中添加几个项目,同时为每个项目指定“amount_in_oz”。

# models.py----------------------------------------------------
class Ingredient(models.Model):
    name = models.CharField(unique=True, max_length=30)
    alcoholic = models.BooleanField(null=False, default=True)

    def __str__(self):
        return self.name

class Cocktail(models.Model):
    name = models.CharField(unique=True, max_length=30)
    garnish = models.CharField(max_length=30)
    recipe = models.ManyToManyField(Ingredient, through='IngredientAmount')

    def __str__(self):
        return self.name

class IngredientAmount(models.Model):
    cocktail = models.ForeignKey(Cocktail, on_delete=models.CASCADE)
    ingredients = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
    amount_in_oz = models.FloatField(null=False)

    def __float__(self):
        return self.amount_in_oz

# admin.py-----------------------------------------------------
class CocktailAdmin(admin.ModelAdmin):
    fields = (('name', 'garnish'), )
    filter_horizontal = ('recipe', )  # Ideally, this line would have allowed it.

admin.site.register(Ingredient)
admin.site.register(Cocktail, CocktailAdmin)

似乎因为中间表需要额外输入,filter_horizo​​ntal 小部件无法处理。

我想知道实现此目的的最佳方法是创建自定义表单或自定义验证? https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form

或者使用formfield_overides? https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides

或者为 ModelAdmin 创建一个新的小部件,例如“filter_horizo​​ntal”,但中间有一个文本框来输入值?

【问题讨论】:

    标签: django-models django-forms django-admin many-to-many


    【解决方案1】:

    您可以使用连接表并进行内联:

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

    from django.contrib import admin
    
    class IngredientAmountInline(admin.StackedInline):
        model = IngredientAmount
    
    class CocktailAdmin(admin.ModelAdmin):
        inlines = [
            IngredientAmountInline,
        ]
    

    【讨论】:

      猜你喜欢
      • 2012-09-11
      • 2016-09-18
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 2021-02-25
      • 2011-04-25
      • 1970-01-01
      • 2021-06-14
      相关资源
      最近更新 更多