Reputation: 4091
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
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