infiniteloop
infiniteloop

Reputation: 2212

'At least one of these fields must be filled' - Can I enforce this requirement in Django models?

Here's a use case:

class Tweet(models.Model):
url_1 = models.CharField(max_length=140)
url_2 = models.CharField(max_length=140)
url_3 = models.CharField(max_length=140)

I'd like the user to specify at least one URL for each Tweet instance.

I know how to enforce this condition in views.py, but I'm wondering if there's a way to configure a Django model such that the user is required to fill in at least one out of a given set of model fields before an instance can be saved. I think that solution would be cleaner.

Thanks!

Upvotes: 1

Views: 587

Answers (2)

nmb.ten
nmb.ten

Reputation: 2228

Since Django 1.2 you can use clean() method of the model where you can make such check. https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#django.db.models.Model.clean

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799520

It can't be done at the model level, but it may be possible to add a constraint at the database level that can enforce this.

Upvotes: 1

Related Questions