简体   繁体   English

如何更改 django model 中的 unique true 的行为?

[英]How to change the behaviour of unique true in django model?

Here I am not deleting the model objects from database.这里我不是从数据库中删除 model 对象。 I am just changing the is_deleted status to True while delete.我只是在删除时将is_deleted状态更改为 True。 But while doing this unique=True gives error for the deleted objects so how can I handle this?但是,这样做时unique=True会为已删除的对象提供错误,那么我该如何处理呢?

I want to exclude is_deleted=True objects from unique True.我想从唯一的 True 中排除is_deleted=True对象。

class MyModel(models.Model):
    name = models.CharField(max_length=20, unique=True)
    is_deleted = models.BooleanField(default=False)


#views
class MyViewSet(ModelViewSet):

    serializer_class = MySerializer
    queryset = MyModel.objects.all()

    def destroy(self, request, *args, **kwargs):
        object = self.get_object()
        object.is_deleted = True
        object.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

You can use a UniqueConstraint [Django docs] with a condition instead of the unique kwarg on the field.您可以使用带有条件的UniqueConstraint [Django docs] ,而不是字段上的unique kwarg。 Although there is a caveat that validation (by forms etc.) will not be done automatically for a unique constraint with a condition and you will need to do that yourself.尽管有一个警告,验证(通过 forms 等)不会针对具有条件的唯一约束自动完成,您需要自己进行验证。

from django.db.models import Q


class MyModel(models.Model):
    name = models.CharField(max_length=20)
    is_deleted = models.BooleanField(default=False)
    
    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['name'], condition=Q(is_deleted=False), name='unique_undeleted_name')
        ]

Since , you can work with Django's constraint API , you can then specify a UniqueConstraint [Django-doc] that has a condition:由于 ,您可以使用Django 的约束 API ,然后您可以指定具有条件的UniqueConstraint [Django-doc]

class MyModel(models.Model):
    #            no unique=True ↓
    name = models.CharField(max_length=20)
    is_deleted = models.BooleanField(default=False)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['name'],
                name='unique_name_not_deleted',
                condition=Q(is_deleted=False)
            )
        ]

It is of course the database that enforces this, and thus some databases might not have implemented that feature.当然是数据库强制执行此功能,因此某些数据库可能没有实现该功能。

You may use following also:您也可以使用以下内容:

class Meta:
       unique_together = ("name", "is_deleted")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM