Ad
Unique Database Entry Determined By Attributes
I have the following class:
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=200)
age = models.CharField(max_length=200)
and I make two identical instances of this class:
alex_1 = Person(name='Alex', age=30)
alex_1.save()
alex_2 = Person(name='Alex', age=30)
alex_2.save()
This will save 2 entries in the person database. Is there any way to prevent the second instance (alex_2
) from being saved as it's technically a duplicate? i.e., can you implement the __eq__
and __hash__
functions for models.Model
instances?
Ad
Answer
As of django-2.2, you can use a UniqueConstraint
[Django-doc] over a combination of the fields:
from django.db.models.constraints import UniqueConstraint
class Person(models.Model):
name = models.CharField(max_length=200)
age = models.CharField(max_length=200)
class Meta:
constraints = [
UniqueConstraint(fields=['name', 'age'], name='person_unique')
]
This thus means that the combination of name
and age
values should be unique. So Person(name='Alex', age=30)
and Person(name='Alex', age=40)
will not raise an error, but two objects Person(name='Alex', age=30)
and Person(name='Alex', age=30)
will result in an error, like:
django.db.utils.IntegrityError: (1062, "Duplicate entry 'Alex-30' for key 'person_unique'")
Before django-2.2, you can use unique_together
[Django-doc]:
class Person(models.Model):
name = models.CharField(max_length=200)
age = models.CharField(max_length=200)
class Meta:
unique_together = ['name', 'age']
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad