对 raw_id_fields 使用 contentType
在我的应用程序中,我有一个模型定义,如下所示:
class SomeModel(models.Model):
someFK = Models.ForeignKey(SomeModel, null=True, blank=True)
otherFK = Models.ForeignKey(OtherModel, null=True, blank=True)
...
该模型保留有关日志的数据,并且要记录的模型不止一种,因此我为每个相关模型放置一个 FK。对于每条记录,仅使用一个 FK,其他 FK 设置 NULL = True。
但当我需要记录其他东西时,我不想改变我的模型。所以我改变了我的模型:
class SomeModel(models.Model):
content_type = models.ForeignKey(ContentType)
content_id = models.IntegerField()
所以我用以下方法来得到我想要的:
content_type.get_object_for_this_type(id=content_id)
没关系。但是当 admin.py 发挥作用时,它会导致问题,因为我有 1.000.000+ 数据要记录一些相关模型,所以我需要使用 raw_id_fields。由于我没有每个相关模型的 FK,因此我必须使用 ContentType 模型和 content_id,但我不知道如何使用 ContentType 来做到这一点?
In my application, i have a model definition like:
class SomeModel(models.Model):
someFK = Models.ForeignKey(SomeModel, null=True, blank=True)
otherFK = Models.ForeignKey(OtherModel, null=True, blank=True)
...
This model keep data about Logs, and there are more than 1 kind of model to be logged, so i place a FK for each related Model. For each record, only one of the FK's is used, other FK's set NULL = True.
But i do not wish to alter my model when i need to log some other thing. So i alter my model so:
class SomeModel(models.Model):
content_type = models.ForeignKey(ContentType)
content_id = models.IntegerField()
So i used following to get what i want:
content_type.get_object_for_this_type(id=content_id)
Its ok. But when admin.py comes into play, it causes problem, because i have 1.000.000+ data for some related models to be logged, so i need to use raw_id_fields. Since i do not have FK for each related model, i must use ContentType model and content_id, but i do not know how to do that using ContentType?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Django grappelli 扩展了 通用查找。
所以你的
ModelAdmin
可能有类似的内容:它解决了我的查找问题。我希望这也能解决你的问题。
Django grappelli extends Django admin functionality in generic lookup.
So your
ModelAdmin
could have something like:It solves my lookup problem. I hope this solve your problem too.
我知道这并不能准确回答您的问题,但您应该使用通用关系而不是多个外键。然后你就可以实现你所需要的最终目标。
I know this doesn't answer your question exactly, but you should be using generic relations instead of multiple foreignkeys. Then you can achieve the end-goal of what you need.