简体   繁体   English

如何从查询中获取另一个对象内的对象?

[英]How to get objects inside another object from a Query?

I don't know how to ask this but is very simple 我不知道怎么问,但是很简单

I have an entity called "State" and another entity called "City". 我有一个名为“州”的实体和另一个名为“城市”的实体。

I'm doing a query to get specific cities with a given parameter: 我正在查询以获取具有给定参数的特定城市:

cities = City.objects.filter(code__exact=12345).values("id","name","state")

And then I serialize the list ( or dict? = in order to get them via JSON: 然后我序列化列表(或dict?=以便通过JSON获得它们:

for c in cities:
    result.append(c)
return HttpResponse(json.dumps(result))

The problem is I'm getting only the state ID but I need another attributes from this object, how I can initialize the state object inside the city or at least get specific attributes from state object. 问题是我仅获得州ID,但我需要该对象的其他属性,即如何初始化城市内的州对象或至少从州对象获取特定属性。

The result from a values() call is a ValueQuerySet , which is special in a few ways. values()调用的结果是ValueQuerySet ,这在ValueQuerySet很特殊。 One of them is: 其中之一是:

A ValuesQuerySet is useful when you know you're only going to need values from a small number of the available fields and you won't need the functionality of a model instance object. 当您知道只需要少量可用字段中的值并且不需要模型实例对象的功能时, ValuesQuerySet很有用 It's more efficient to select only the fields you need to use. 仅选择您需要使用的字段更为有效。

The part in bold is important. 粗体部分很重要。 It means that the result of the queryset will not have the instances of the models, you have to tell it exactly what you need to be fetched. 这意味着查询集的结果将没有模型的实例 ,您必须准确告诉它需要获取的内容。

So, if you know the fields of the state model you want in your result, you can add them in your values clause. 因此,如果您知道要在结果中使用的状态模型的字段,则可以将其添加到values子句中。 If you just put state , it will give you the state id, which is the default identity field. 如果仅输入state ,它将为您提供状态ID,这是默认的标识字段。

cities = City.objects.filter(code__exact=12345).values("id",
                                                       "name",
                                                       "state__name",
                                                       "state__id")

If you are doing this just to convert the results to json, use the built-in serializers : 如果这样做只是为了将结果转换为json,请使用内置的序列化器

from django.core import serializers
result = serializers.serialize('json',
                               City.objects.filter(code__exact=12345),
                               fields=('id', 'name', 'state__name', 'state__id'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM