gpt4 book ai didi

python - 关于FK模型继承的django动态相关名称

转载 作者:太空狗 更新时间:2023-10-30 02:19:42 25 4
gpt4 key购买 nike

我正在尝试通过对另一个类属性执行操作来动态设置类属性。我的代码是这样的

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',我可以轻松调用 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'

我哪里错了?

最佳答案

答案很简单,根据 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

希望对你有帮助

关于python - 关于FK模型继承的django动态相关名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27975712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com