Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django models avoid duplicates

In models:

class Getdata(models.Model):
    title = models.CharField(max_length=255)
    state = models.CharField(max_length=2, choices=STATE, default="0")
    name = models.ForeignKey(School)
    created_by = models.ForeignKey(profile)

    def __unicode__(self):
        return self.id()

In templates:

<form>
    <input type="submit" value="save the data" />
</form> 

If the user clicks on the save button and the above data is saved in the table, how to avoid the duplicates, i.e. if the user again clicks on the same submit button there should not be another entry for the same values. Or is it something that has to be handled in views?

like image 766
Hulk Avatar asked Jun 16 '10 11:06

Hulk


People also ask

How do I avoid duplicates in Django?

Use the get_or_create() Method in Django When we create duplicate objects multiple times, this method helps us avoid creating them multiple times.

What is unique in Django?

unique=True sets the field to be unique i.e. once entered a value in a field, the same value can not be entered in any other instance of that model in any manner. It is generally used for fields like Roll Number, Employee Id, etc which should be unique.


1 Answers

If an individual field needs to be unique, then you just add unique=True:

class Getdata(models.Model):
    title = models.CharField(max_length=255, unique=True)
    state = models.CharField(max_length=2, choices=STATE, default="0")
    name = models.ForeignKey(School)
    created_by = models.ForeignKey(profile)

If you want a combination of fields to be unique, you need unique_together:

class Getdata(models.Model):
    title = models.CharField(max_length=255)
    state = models.CharField(max_length=2, choices=STATE, default="0")
    name = models.ForeignKey(School)
    created_by = models.ForeignKey(profile)
    class Meta:
        unique_together = ["title", "state", "name"]
like image 130
Mike DeSimone Avatar answered Oct 07 '22 18:10

Mike DeSimone