我试图通过对另一个类属性执行操作来动态设置类属性。我的代码就像这样
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
这是为了动态设置相关名称,以便对于类Item和用户',我可以轻松调用user.created_items.all()。
这给了我错误
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'
我哪里出错?
答案 0 :(得分:7)
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
希望有所帮助