views:

28

answers:

1
class Votes(models.Model):  
    field1 = models.ForeignKey(Blah1)  
    field2 = models.ForeignKey(Blah2)  
    class Meta:  
            unique_together = (("field1","field2"),)

I am using this code as one of my models. Now i wanted to know two things:
1. It doesn't show any error and it saved an entry which wasn't unique together; So is the piece of code correct?
2. How can the unique_together constraint be be validated?

+1  A: 

Looks ok to me. Have you tried the simpler syntax of unique_together = ("field1","field2") just in case there's a subtle bug?

Either way, as said here "It's used in the Django admin and is enforced at the database level (i.e., the appropriate UNIQUE statements are included in the CREATE TABLE statement)."

Did you update your schema (with a migration, a drop and fresh syncdb or manual SQL) to add the appropriate constraints?

stevejalim
I added this constraint later and not during the creation of the table. So i had to create the db again and it worked. Thanks. But is there any way in which such constraint addition can take place later and things work? Also what about handling the error?
zubinmehta
Sounds like the constraint is gracefully enforced by the admin, so a poke around inside django.contrib.admin will probably help. And in the future, if you have to add on a unique_together constraint, a migrations app like South (south.aeracode.org) should be able to help you out.
stevejalim