3

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?

damon
  • 8,127
  • 17
  • 69
  • 114

1 Answers1

2

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.

Community
  • 1
  • 1
Skylar Saveland
  • 11,116
  • 9
  • 75
  • 91
  • thanks for the reply.. how do I do the datamigration for this?I can add a value for creator in the forwards() method ,but how do I set the uniqueness for each record? – damon Dec 28 '12 at 08:48
  • I know it may be heresy; but, I've never liked south and don't really know how to use it. – Skylar Saveland Dec 30 '12 at 07:39