Home "rotating" columns and unique_together
Reply: 0

"rotating" columns and unique_together

user1393
1#
user1393 Published in April 19, 2018, 8:58 pm

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?

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO