在Django queryset中从相关对象请求其他字段

时间:2019-02-28 12:40:59

标签: django django-models django-queryset

说我有两个模型,ParentChild

Child模型与Parent

有fk关系
Class Child(models.Model):
     parent = models.ForeignKey('Parent', related_name='family')

我想为Child编写一个查询集并将其序列化为geojson,但是,我也希望查询集包含Parent中ID之外的其他字段。也许我对select_related()不清楚。

这在功能上提供了相同的查询,而没有来自Parent的其他字段:

qs = Child.objects.filter(...).select_related('parent')

props = {
    'geoJson' : serializers.serialize('geojson', list(qs)),
}

如果我将.select_related('parent').values(...)设置为所需字段,则视图将在要求上出现错误:

'dict' object has no attribute '_meta'

.select_related('parent').only(...)引发:

Field Child.parent cannot be both deferred and traversed using select_related at the same time

构造该查询集以从相关对象请求额外字段的正确方法是什么?我对查询中的selected_related有什么误解?谢谢

.values()追溯:

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/channels/handler.py" in process_exception_by_middleware
  237.             return super(AsgiHandler, self).process_exception_by_middleware(exception, request)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File ".pyenv/versions/3.6.3/lib/python3.6/contextlib.py" in inner
  52.                 return func(*args, **kwds)

File "project/utils/helpers.py" in _decorated
  29.             return view(request, *args, **kwargs)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/htmlmin/decorators.py" in minify
  13.         response = f(*args, **kwargs)

File "/causes/views.py" in cause
  197.         'activityJson' : serializers.serialize('geojson', list(qs)),

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/serializers/__init__.py" in serialize
  129.     s.serialize(queryset, **options)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/core/serializers/base.py" in serialize
  81.             self.start_object(obj)

File ".pyenv/versions/3.6.3/lib/python3.6/site-packages/django/contrib/gis/serializers/geojson.py" in start_object
  35.             for field in obj._meta.fields:

1 个答案:

答案 0 :(得分:1)

您的误解是这与select_related 没有任何关系。该方法仅用于进行更有效的查询,而不会以任何方式影响从序列化程序返回的数据。

Django的内置序列化器非常基础,并且不支持这样的嵌套对象。如果那是您想要的,则应使用Django REST框架,该框架实现了功能更强大的序列化程序,可以以多种方式序列化嵌套对象。