Home "rotating" columns and unique_together
Reply: 0

"rotating" columns and unique_together

user1393 Published in July 16, 2018, 6:21 am

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?


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.56796 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO