Gringo Suave
Gringo Suave

Reputation: 31910

Is it possible to group Model fields in Django?

Working on a Calendar app, and would like each Event model instance to have one of the {allday|start,end} fields filled out. That is, either the allday field entered, or the start+end fields, but not both.

How can I model this and have it work correctly in the admin app? I'd like one of the group to be required.

Upvotes: 0

Views: 967

Answers (1)

manji
manji

Reputation: 47978

Create your model with all 3 fields, and override the clean method (called when validating the model) to check on your conditions:

def clean(self):
    if not self.allday: # allday not present
        if not self.start or not self.end: # start and/or end not present
            raise ValidationError('error message...')
    else:
        if self.start or self.end:     # allday present but also start and/or end
            raise ValidationError('error message...')

More information on clean: Model.clean()

Upvotes: 3

Related Questions