Home "rotating" columns and unique_together
Reply: 1

"rotating" columns and unique_together

Pelle G
1#
Pelle G Published in 2017-12-07 11:33:47Z

I have a django model:

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)

Is it possible to create another unique_together contraint, where "start_node" and "end_node" fields are switched?

Explained:

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

I want a exception raised when I'm saving obj3. But how to?

Pelle G
2#
Pelle G Reply to 2017-12-07 20:00:30Z

I did an overwrite of clean() method and asked the class for the other combinations, if it existed it would raise a 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"),)
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.300816 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO