python - django 序列化程序查询数据库的外键 ID

标签 python django serialization django-serializer

我使用 django 序列化程序序列化了几个对象,但问题是每个序列化都从数据库中查询外键的 id,而不是仅仅从对象中获取它,例如

class QBAccount(CompanyModel):
    company = models.ForeignKey(Company)

>>> from deretoapp.models import QBAccount
>>> import logging
>>> l = logging.getLogger('django.db.backends')
>>> l.setLevel(logging.DEBUG)
>>> l.addHandler(logging.StreamHandler())
>>> a = QBAccount.allobjects.all()[0]
>>> from django.core import serializers
>>> serializers.serialize('python', [a])
(0.000) SELECT `deretoapp_company`.`id`, ... FROM `deretoapp_company` WHERE `deretoapp_company`.`id` = 45995613-adeb-488f-9556-d69e856abe5f ; args=(u'45995613-adeb-488f-9556-d69e856abe5f',)
[{'pk': u'3de881eb-8409-4089-8de8-6e24f7281f37', 'model': u'deretoapp.qbaccount', 'fields': {... 'company': u'45995613-adeb-488f-9556-d69e856abe5f' ....}}]

有没有办法在不修改 Django 代码的情况下改变这种行为?我知道 a.company.id 将查询公司表(这在理想世界中不应该发生)但是序列化器中是否有一个选项以便它执行类似 a.company_id 的操作这不会查询数据库

>>> django.VERSION
(1, 3, 1, 'final', 0)

最佳答案

我最终修改了 django python 序列化程序,以便它直接获取引用对象的 id 而不是从 db 获取它

from django.core.serializers.python import Serializer as PythonSerializer
from django.core.serializers.python import Deserializer

class Serializer(PythonSerializer):
    internal_use_only = False

    def handle_fk_field(self, obj, field): 
        if not self.use_natural_keys:
            # directly get the id
            self._current[field.name] = getattr(obj, field.attname)
            return

        return super(Serializer, self).handle_fk_field(obj, field)

我不确定它是否处理所有 ForeighKey 用例,但它适用于像 company = models.ForeignKey(Company) 这样的简单情况

还需要在settings.py中注册serializer

SERIALIZATION_MODULES = { 'python' : 'myapp.serializers.python' }

我还提交了 bug为此,现在已在 django trunk 中修复。 see changset

关于python - django 序列化程序查询数据库的外键 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9035726/

相关文章:

python - Heroku & Django : "OSError: No such file or directory: '/app/{myappname}/static'"

python - 我需要有关如何在 Django 中实现复选框的建议

javascript - jQuery 将表单序列化为 JSON 对象但忽略占位符

json - GWT POJO-JSON 映射器?

php - 无法获取未序列化的数据

python - 在Python中解压int + long long

python - 如何用 Homebrew gfortran 替换我的 HPC gfortran?

python - 在 PyQt 中绘制多边形

python - 在 Matplotlib 中,如何避免 axvspan 重叠?

python - 无效的 http_host header