Reputation: 1197
I want to use user
foreignkey to many models. I can't use this type of method. Is any possible way to give common name to all foreignkey. I want to access x.created
or x.updated
in every template.
class Model_one(models.Model):
--
--
created = models.ForeignKey(User,related_name="created")
updated = models.ForeignKey(User,related_name="updated")
class Model_two(models.Model):
--
--
created = models.ForeignKey(User,related_name="created")
updated = models.ForeignKey(User,related_name="updated")
class Model_three(models.Model):
--
--
created = models.ForeignKey(User,related_name="created")
updated = models.ForeignKey(User,related_name="updated")
Upvotes: 0
Views: 2347
Reputation: 50796
To generalize your approach you could do something like that:
class BaseModel(models.Model):
created = models.ForeignKey(User,related_name="created_%(class)s_objects")
updated = models.ForeignKey(User,related_name="updated_%(class)s_objects")
class Meta:
abstract = True
class ModelOne(BaseModel):
# your model one fields
class ModelTwo(BaseModel):
# your model two fields
With this approach you
don't need to define the same fields on all models explicitly because you inherit from BaseModel
.
The special syntax automatically creates backward-relations with the right class names. Therefore user.created_modelone_objects.all()
will give you all the objects an user has created.
Upvotes: 4