Django Admin:has_delete_permission

vjrehmav  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(113)

我需要实施一项禁止从食谱中删除最后一种成分的禁令。以便配方不会因没有配料而留空,或者在删除最后一种配料时删除配方。
模型化

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,但它不起作用

qc6wkl3g

qc6wkl3g1#

如果你想 * 禁止从食谱中删除 * 最后一种成分:
但是如果你一开始选择删除所有IngredientRecipe对象,这个方法就不起作用了,因为这个方法只是禁用了Inline对象的删除按钮

class IngredientRecipeInline(admin.TabularInline):
    model = IngredientRecipe

    def has_delete_permission(self, request, obj=None):    
        if obj and obj.recipes.ingredients.count() == 1:
            return False
        return super().has_delete_permission(request, obj)

字符串
或者如果你想在删除最后一种配料时删除*配方,你可以这样做:

class IngredientRecipe(models.Model):

    def delete(self, using=None, keep_parents=False):
        if self.recipes.ingredients.count()==1:
            self.recipes.delete()
        super().delete(using, keep_parents)

相关问题