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")
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.