对 raw_id_fields 使用 contentType

发布于 2024-09-13 03:27:29 字数 779 浏览 2 评论 0原文

在我的应用程序中,我有一个模型定义,如下所示:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苹果你个爱泡泡 2024-09-20 03:27:29

Django grappelli 扩展了 通用查找
所以你的 ModelAdmin 可能有类似的内容:

class SomeModelAdmin(ModelAdmin):
    related_lookup_fields = {
        'generic': [['content_type', 'object_id'], ],
    }

Result

它解决了我的查找问题。我希望这也能解决你的问题。

Django grappelli extends Django admin functionality in generic lookup.
So your ModelAdmin could have something like:

class SomeModelAdmin(ModelAdmin):
    related_lookup_fields = {
        'generic': [['content_type', 'object_id'], ],
    }

Result

It solves my lookup problem. I hope this solve your problem too.

合约呢 2024-09-20 03:27:29

我知道这并不能准确回答您的问题,但您应该使用通用关系而不是多个外键。然后你就可以实现你所需要的最终目标。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文