我需要实施一项禁止从食谱中删除最后一种成分的禁令。以便配方不会因没有配料而留空,或者在删除最后一种配料时删除配方。
模型化
class Recipe(models.Model):
name = models.CharField(
max_length=200
)
author = models.ForeignKey(
User,
related_name='recipes',
on_delete=models.CASCADE,
null=True,
)
text = models.TextField(
)
image = models.ImageField(
upload_to='recipes/'
)
cooking_time = models.PositiveSmallIntegerField(
validators=(
MinValueValidator(
MIN_VALUE
),
MaxValueValidator(
MAX_VALUE
),
)
)
ingredients = models.ManyToManyField(
Ingredient,
related_name='recipes',
through='IngredientRecipe'
)
字符串
管理员
class RecipeAdmin(admin.ModelAdmin):
list_display = ('name',
'author',
)
list_filter = ('name', 'author',
('tags', admin.RelatedOnlyFieldListFilter),)
inlines = (IngredientRecipeInline, TagRecipeInline)
class IngredientRecipeInline(admin.TabularInline):
model = IngredientRecipe
min_num = 1
class IngredientAdmin(admin.ModelAdmin):
list_display = ('name',
'measurement_unit',
)
class IngredientRecipeAdmin(admin.ModelAdmin):
list_display = ('recipe',
'ingredient',
'amount',
)
list_filter = ('ingredient',)
型
我尝试min_num = 1,但它不起作用
1条答案
按热度按时间qc6wkl3g1#
如果你想 * 禁止从食谱中删除 * 最后一种成分:
但是如果你一开始选择删除所有IngredientRecipe对象,这个方法就不起作用了,因为这个方法只是禁用了Inline对象的删除按钮
字符串
或者如果你想在删除最后一种配料时删除*配方,你可以这样做:
型