I have a model with three classes: PendingAuthorisation
, Director
, and Member
. Director
and Member
instances are considered inactive if they have a corresponding PendingAuthorisation
.
My problem is quite how to model this. I would ideally like PendingAuthorisation
to have just one field, defers
, which can ref开发者_StackOverflower to either a Director
or a Member
. If I create a foreign key in both Director
and Member
then I need to have two differently-named relations, and when using a PendingAuthorisation
I would need to check both to find the object it is deferring. In no case should a PendingAuthorisation
be deferring one object of each type.
Any suggestions on how to model this?
I'd recommend having two foreign keys (with a sanity check in your save method to make sure that they're not both set), and then a property to return back the object that's set.
Think about something like:
from django.db import models
class PendingAuthorization(models.Model):
director = models.ForeignKey(Director, null=True, blank=True)
member = models.ForeignKey(Member, null=True, blank=True)
def save(self, *args, **kwargs):
if self.director and self.member:
raise ValueError, 'Both a director and member are set; this is not allowed.'
return super(PendingAuthorization, self).save(*args, **kwargs)
@property
def defers(self):
if self.director:
return self.director
if self.member:
return self.member
return None
精彩评论