Django: How to define the models when parent model has two foreign keys come from one same model?
I want to define two model fields: created_by, modified_by in a parent model, they will be acting as common fields for the child models.
class ExtendedModel(models.Model):
created_by = models.ForeignKey(User,related_name='r_created_by')
modified_by = models开发者_运维百科.ForeignKey(User,related_name='r_modified_by')
class Meta:
abstract = True
class ChildModel1(ExtendedModel):
pass
class ChildModel2(ExtendedModel):
pass
this gives errors as ChildModel1 and ChildModel2 has related_name clashed with each other on their created_by and modified_by fields.
The Django docs explain how to work around this: http://docs.djangoproject.com/en/dev/topics/db/models/#abstract-related-name
class ExtendedModel(models.Model):
created_by = models.ForeignKey(User,related_name='"%(app_label)s_%(class)s_created_by')
modified_by = models.ForeignKey(User,related_name='"%(app_label)s_%(class)s_modified_by')
class Meta:
abstract = True
class ChildModel1(ExtendedModel):
pass
class ChildModel2(ExtendedModel):
pass
精彩评论