简体   繁体   中英

django model with unique combination of two fields

I have a django model as below

class MySubject(models.Model):
    name=models.CharField(unique=True,max_length=50)
    description=models.TextField(blank=True)
    slug=models.SlugField(editable=False)

    class Meta:
        verbose_name_plural="MySubjects"

    def __unicode__(self):
        return self.name

    def save(self,*args,**kwargs):
        self.name=self.name.strip()
        self.slug=slugify(self.name)
        super(MySubject,self).save(*args,**kwargs)

    @models.permalink
    def get_absolute_url(self):
        return ('subject_detail',(),{'slug':self.slug})

I need to make the creator+ name unique ,sothat I can call

subject,status=MySubject.objects.get_or_create(name__iexact=name.strip(),creator= request.user,defaults={'name':name,'description':name,'creator':request.user})

Is the following ,the right way to do this?

class MySubject(models.Model):
        name=models.CharField(max_length=50)
        creator = models.ForeignKey(User,null=True)
        description=models.TextField(blank=True)
        slug=models.SlugField(editable=False)

        class Meta: 
            verbose_name_plural="MySubjects"
            unique_together = ('name', 'creator',)
         ...

I guess I have to do a migration using south after making the change..Do I have to do schemamigration alone or do I have to do a datamigration ?

Adding a unique constraint is a schema migration. However, if you have existing data that would cause an integrity error, you would need a data migration, as well.

If you really want case-insensitive unique constraint, it's a little more complicated:

Case insensitive unique model fields in Django?

see also: https://code.djangoproject.com/ticket/14564

If you always use get_or_create with iexact, you may be ok. But, you should not manually create two with name as "foo" and "fOo", because, this would be allowed and then your call to get_or_create would cause a MultipleObjectsReturned .. if I'm thinking correctly.

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