Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make uniques in Django Models? And also index a column in Django

This is my simple Django database model. It's for a 5-star rating system.

class Rating(models.Model):
    content = models.OneToOneField(Content, primary_key=True)
    ip =  models.CharField(max_length=200, blank=True)
    rating = models.IntegerField(default=0)

As you can see, it is linked to "Content", which is the table for my documents. My question is:

  • How do I make content+ip unique...so that it multiple content is okay, but multiple content AND IP is not okay (do not want the user to rate twice).
  • How do I create a data-base index for content and ip...because I will always be selecting those (to compare if it is already in the database).
like image 720
TIMEX Avatar asked Nov 25 '09 00:11

TIMEX


3 Answers

This is the answer for those who are using Django 3.0+.

It's better to use UniqueConstraint ( as per the docs ) for making uniques.

 class Rating(models.Model):
    ...

    class Meta:
        constraints = [ models.UniqueConstraint(fields=['content', 'ip'], name="unique-content-ip") ]
        indexes = [ models.Index(fields=['content', 'ip']) ]

And hence you can define multiple constraints & indexes.

like image 69
adshin21 Avatar answered Nov 01 '22 13:11

adshin21


Regarding your first question: You should look at unique_together, since this could solve your issue.

class Rating(models.Model):
    content = models.OneToOneField(Content, primary_key=True)
    ip =  models.CharField(max_length=200, blank=True)
    rating = models.IntegerField(default=0)

    class Meta:
        unique_together= (('content', 'ip'),)
like image 33
ikkebr Avatar answered Nov 01 '22 11:11

ikkebr


BTW, if, as it appears from your terminology, you're using IP addresses as standing for users' identities, please don't -- it's a seriously horrible idea. Users coming in through their ISP will get their IPs changed at random times, so they might vote twice; users on a laptop connecting at various coffee shops, libraries, &c, will have always-varying IPs; users sharing a connection (e.g., apartment-mates), or even every single one of users coming in from a University campus, might get the same IP address via NAT, so only one will be able to vote... it's hard to think of any worse way to represent individuals' identities!-)

If your use of the name ip for your "user identity" field is accidental and has nothing to do with using IP addresses there, I apologize, but in that case please do rename that field!-)

like image 33
Alex Martelli Avatar answered Nov 01 '22 13:11

Alex Martelli