Doran
Doran

Reputation: 4091

Django enforce that the value of OneToOneField belongs to a ForiegnKey related object set

I have models similar to what is below:

class Submission(models.Model):
    round = models.ForeignKey('Round',related_name='submissions')
    text = models.TextField()

class Round(models.Model):
    favorite = models.OneToOneField('Submission',related_name='round_favorite+',null=True)

Is there any built-in way to enforce that Round.favorite be in Round.submissions? ie:

assert(favorite in round.submissions.all())

If not, what is the best way to enforce this assertion? The pre_save signal? Overriding Model.save?

Upvotes: 0

Views: 80

Answers (1)

Pratik Mandrekar
Pratik Mandrekar

Reputation: 9568

You should override the save of the Round model to ensure that the favorite submission exists and if not save it.

If you try to save the Round model when the favorite doesn't exist ins Submission, there will be an exception thrown, most likely Submission.DoesNotExist. So you can use the exception to save and try again.

Upvotes: 1

Related Questions