views:

22

answers:

1

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.

+3  A: 

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
mazelife
I should add that this works slightly differently based on the version of Django you're using, so check the docs for your version to be sure. For example, in 1.1, I don't think the %(app_label)s substitution works, although %(class)s does.
mazelife
this works perfectly, I missed that part in the doc previously. thanks for the answer.
alvinSJ