如何验证跨外键的唯一性约束(django) [英] How to validate uniqueness constraint across foreign key (django)

查看:196
本文介绍了如何验证跨外键的唯一性约束(django)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下(简化)数据结构:

I have the following (simplified) data structure:

Site
-> Zone
   -> Room
      -> name

我希望每个房间的名称对于每个网站都是唯一的。

I want the name of each Room to be unique for each Site.

我知道,如果我只想要每个区域的唯一性,我可以这样做:

I know that if I just wanted uniqueness for each Zone, I could do:

class Room(models.Model):
    zone = models.ForeignKey(Zone)
    name = models.CharField(max_length=255) 

    class Meta:
        unique_together = ('name', 'zone')

但是我不能做我真正想要的,是:

But I can't do what I really want, which is:

class Room(models.Model):
    zone = models.ForeignKey(Zone)
    name = models.CharField(max_length=255) 

    class Meta:
        unique_together = ('name', 'zone__site')

我尝试添加一个validate_unique方法,如这个问题

I tried adding a validate_unique method, as suggested by this question:

class Room(models.Model):
    zone = models.ForeignKey(Zone)
    name = models.CharField(max_length=255) 

    def validate_unique(self, exclude=None):
        qs = Room.objects.filter(name=self.name)
        if qs.filter(zone__site=self.zone__site).exists():
            raise ValidationError('Name must be unique per site')

        models.Model.validate_unique(self, exclude=exclude)

但是我必须误会这个点/ validate_unique,因为当我保存Room对象时没有被调用。

but I must be misunderstanding the point/implementation of validate_unique, because it is not being called when I save a Room object.

实现此检查是正确的方法?

What would be the correct way to implement this check?

推荐答案

保存模型时,方法不会自己调用。
这样做的一个方法是保存模型时调用validate_unique方法的自定义保存方法:

Methods are not called on their own when saving the model. One way to do this is to have custom save method that calls the validate_unique method when model is saved:

class Room(models.Model):
    zone = models.ForeignKey(Zone)
    name = models.CharField(max_length=255) 

    def validate_unique(self, exclude=None):
        qs = Room.objects.filter(name=self.name)
        if qs.filter(zone__site=self.zone__site).exists():
            raise ValidationError('Name must be unique per site')


    def save(self, *args, **kwargs):

        self.validate_unique()

        super(Room, self).save(*args, **kwargs)

这篇关于如何验证跨外键的唯一性约束(django)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆