"转动"列和unique_together

时间:2017-12-07 11:33:48

标签: python django postgresql django-models

我有一个django模型:

class ShortestRoads2(models.Model):
    start_node = models.ForeignKey('Nodes', related_name='start_node2', null=True)
    end_node = models.ForeignKey('Nodes', related_name='end_node2', null=True)
    map = models.ForeignKey('project.MapProject', null=True)

    def __str__(self):
        return str(self.start_node) + ' to ' + str(self.end_node)

    class Meta:
        unique_together =(("start_node", "end_node", "map"),)


class Nodes(models.Model):
    number = models.IntegerField(null=True, unique=True)
    geom_node = models.PointField(spatial_index=True)

是否可以创建另一个unique_together约束,其中" start_node"和" end_node"字段是否已切换?

说明:

obj = ShortestRoads2()
obj.start_node = Nodes.objects.create(number=x1)
obj.end_node = Nodes.objects.create(number=x2)
obj.save() # Object created

obj2 = ShortestRoads2()
obj2.start_node = Nodes.objects.create(number=x1)
obj2.end_node = Nodes.objects.create(number=x2)
obj2.save()  # Raising as expected: IntegrityError 

obj3 = ShortestRoads2()
obj3.start_node = Nodes.objects.create(number=x2) #Notice varible change
obj3.end_node = Nodes.objects.create(number=x1)  #Notice variable change
obj3.save() # Object created

我希望在保存obj3时引发异常。但是如何?

1 个答案:

答案 0 :(得分:0)

我覆盖了clean()方法并向类询问了其他组合,如果它存在则会引发IntegrityError

class ShortestRoads2(models.Model):
    start_node = models.ForeignKey('Nodes', related_name='start_node2', null=True)
    end_node = models.ForeignKey('Nodes', related_name='end_node2', null=True)
    map = models.ForeignKey('project.MapProject', null=True)

    def __str__(self):
        return str(self.start_node) + ' to ' + str(self.end_node)

    def clean(self):
        if ShortestRoads2.objects.filter(start_node=self.end_node, end_node=self.start_node).exists():
            raise IntegrityError({'end_node': ['combinations allready exist', ]})

    def save(self, *args, **kwargs):
        self.clean_fields(exclude='length')
        self.clean()
        self.validate_unique()
        super(ShortestRoads2, self).save(*args, **kwargs)

    class Meta:
        unique_together =(("start_node", "end_node", "map"),)