[英]django dynamic related name on FK model inhertiance
I am trying to set a class attribute dynamically, by performing an operation on another class attribute.我试图通过对另一个类属性执行操作来动态设置类属性。 My code goes like this我的代码是这样的
class LastActionModel(BaseModel):
"""
Provides created_by updated_by fields if you have an instance of user,
you can get all the items, with Item being the model name, created or updated
by user using user.created_items() or user.updated_items()
"""
created_by = models.ForeignKey(
settings.AUTH_USER_MODEL, blank=True, null=True,
related_name = lambda self:'%s_%s' %('created', \
self._meta.verbose_name_plural.title().lower())
)
updated_by = models.ForeignKey(
settings.AUTH_USER_MODEL, blank=True, null=True,
related_name = lambda self:'%s_%s' %('updated', \
self._meta.verbose_name_plural.title().lower())
)
class Meta:
abstract = True
This is to dynamically set the related name so that for a class Item, and a User 'user', i can easily call user.created_items.all().这是为了动态设置相关名称,以便对于类 Item 和用户“用户”,我可以轻松调用 user.created_items.all()。
This is giving me the error这给了我错误
super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only)
File "/home/pywebapp/venv/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 113, in contribute_to_class
'app_label': cls._meta.app_label.lower()
TypeError: Error when calling the metaclass bases
unsupported operand type(s) for %: 'function' and 'dict'
where i am going wrong?我哪里出错了?
the answer was pretty simple, as per docs根据文档,答案非常简单
class LastActionModel(BaseModel):
"""
Provides created_by updated_by fields if you have an instance of user,
you can get all the items, with Item being the model name, created or updated
by user using user.created_items() or user.updated_items()
"""
created_by = models.ForeignKey(
'users.User', blank=True, null=True,
related_name = 'created_%(class)ss'
)
updated_by = models.ForeignKey(
'users.User', blank=True, null=True,
related_name = 'updated_%(class)ss'
)
class Meta:
abstract = True
hope it helps希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.