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?
Use the get_or_create() Method in Django When we create duplicate objects multiple times, this method helps us avoid creating them multiple times.
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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With