Lune Logo

© 2025 Lune Inc.
All rights reserved.

support@lune.dev

Want to use over 200+ MCP servers inside your coding tools like Cursor?

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.

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:

PYTHON
class 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:

  • Prevent duplicate entries where all non-None fields match.
  • For example, these should be considered duplicates:
    1. street="123 Elm", house_number=None, city="Springfield", state="CA", zip_code="12345"
    2. 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!

0

Comments 0

Answers 0

Views 70

0 Answers

Discussion

No comments yet.