Django模型 - 继承字段(Sorta?)

时间:2011-09-08 05:18:11

标签: django model

如何构建RegisteredSubscriber模型以实现下面伪代码中描述的功能?

我想我可以为每个字段实现一个函数,但这看起来不正确并且有点实用。想法?

 61 class RegisteredSubscriber(Subscriber):
 62     user = models.ForeignKey(User)
 63     first_name = self.user.first_name
 64     last_name = self.user.last_name
 65     email = self.user.email
 66
 67 class AnonymousSubscriber(Subscriber):
 68     first_name = models.CharField(max_length = 100)
 69     last_name = models.CharField(max_length = 100, blank = True)
 70     email = models.EmailField(unique = True)

好的,这实现了我想要的功能,但我确定它不合适。思考?如果我犯了设计错误,那么正式方法会是什么?

 59 class RegisteredSubscriber(Subscriber):
 60     user = models.ForeignKey(User, unique = True)
 61     first_name = 'candy'
 62     last_name = 'candy'
 63     email = 'candy'
 64
 65     def __init__(self, *args, **kwargs):
 66         super(RegisteredSubscriber, self).__init__(*args, **kwargs)
 67         
 68         if self.id:
 69             self.first_name = self.user.first_name
 70             self.last_name = self.user.last_name
 71             self.email = self.user.email
 72
 73     def __unicode__(self):
 74         return u'%s %s' % (self.first_name, self.last_name)

1 个答案:

答案 0 :(得分:0)

由于您与ForeignKey的关系已User,因此我不了解first_name, last_name, email模型中RegisteredSubscriber字段的必要性,除非我是遗漏了什么。如果您想使用first_name实例访问RegisteredSubscriber等字段,ForeignKey关联版允许您使用__。 例如:user__first_name