[英]Django Multiple ForeignKey and same related name
I want to use user
foreignkey to many models. 我想将user
键用于许多模型。 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. 我想在每个模板中访问x.created
或x.updated
。
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
. 不需要显式定义所有模型上的相同字段,因为您从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. 因此user.created_modelone_objects.all()
将为您提供用户创建的所有对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.