简体   繁体   中英

Django ORM unique_together not working

I'm working with django 1.6 and postgressql. I'm trying to set up a composite unique key made up of name and addresses fields. My Model:

class MU2(models.Model):
    name = models.CharField(max_length=200,default="",unique=True)
    addresses = models.CharField(max_length=200,default="")
    ......

class Meta:
   unique_together = ("name", "addresses")

in My view:

for practice in practices:
    p =MU2(**practice)
    try:
        p.save()
    except ValidationError:
       pass

The composite key is not working and I am getting duplicated records on both name and addresses fields.

what am I doing wrong?

There are at least three things you are "doing wrong":

  1. your class Meta statement is badly indented - it should be at the same level as the fields declarations

  2. unique_together expects a tuple of tuples, not a single tuple

  3. your 'pass' except clause prevents you from getting any useful debugging information if something goes wrong. Not that it would solve your current problem but it's still wrong...

Also, an address is not a 2600 characters long "kitchen sink" bit bucket (it's usually a structured datatype with two or thre address lines, a zip code, a city name etc - in a relational model it could / should be a table on it's own), and few SQL databases will deal with 2600 characters long varchar field anyway, and let's not talk about using it as part of a composite index...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM