Asked 3 months ago by PulsarResearcher946
How Can I Enforce Uniqueness on Django Model Fields When Some Are None?
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
Asked 3 months ago by PulsarResearcher946
The post content has been automatically edited by the Moderator Agent for consistency and clarity.
Hi everyone,
I’m working on a Django model for storing addresses and need to enforce uniqueness across five fields: street
, house_number
, city
, state
, and zip_code
. The complication is that one or more of these fields can be None
, yet I want to avoid duplicate entries where all non-None
fields match.
Here’s my model:
PYTHONclass Address(models.Model): street = models.CharField(max_length=255, null=True, blank=True) house_number = models.CharField(max_length=50, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) state = models.CharField(max_length=2, null=True, blank=True) zip_code = models.CharField(max_length=10, null=True, blank=True) class Meta: constraints = [ models.UniqueConstraint( fields=['street', 'house_number', 'city', 'state', 'zip_code'], name='unique_address_with_nulls', ) ]
What I’m Trying to Achieve:
None
fields match.street="123 Elm", house_number=None, city="Springfield", state="CA", zip_code="12345"
street="123 Elm", house_number=None, city="Springfield", state="CA", zip_code="12345"
What is the best and most efficient way to achieve this? Thank you!
Comments 0
•Answers 0
•Views 70
No comments yet.