选择select_related()后的特定字段只有()

时间:2016-07-14 16:13:35

标签: python django django-1.9

我有2个型号与OneToOneField相关联:

class Person(TimeStampedModel, StatusModel):
    name = models.CharField(max_length=300)
    slug = models.SlugField(max_length=300)

class Card(TimeStampedModel, StatusModel):
    title = models.CharField(max_length=300)
    year = models.IntegerField()
    comment = models.TextField(blank=True)
    featured = models.BooleanField(default=False)
    person = models.OneToOneField(Person, on_delete=models.CASCADE)

我想仅从nametitle模型查询PersonCard字段。

我尝试了几种方法,但没有一种方法有效。

第一次尝试

Person.objects.filter(slug=slug).only('name', 'card__title')

但生成的查询不包含card__title

SELECT "core_person"."id", "core_person"."name" FROM "core_person" 
WHERE "core_person"."slug" = some-name

第二次尝试

Person.objects.filter(slug=slug).select_related('card').only('name')

但生成的查询包含Card的所有字段:

SELECT "core_person"."id", "core_person"."name", "core_card"."id",
       "core_card"."title", "core_card"."year", "core_card"."comment", 
       "core_card"."featured" 
FROM "core_person" 
LEFT OUTER JOIN "core_card" ON ("core_person"."id" = "core_card"."person_id")
WHERE "core_person"."slug" = some-name

第三次尝试

Person.objects.filter(slug=slug).select_related('card').only('name', 'card__title')

但它引发了奇怪的例外:

django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'card'. Choices are: card

期望的结果

有没有办法接收下面的查询而不使用.values()

SELECT "core_person"."id", "core_person"."name", "core_card"."id",
       "core_card"."title"
FROM "core_person" 
LEFT OUTER JOIN "core_card" ON ("core_person"."id" = "core_card"."person_id")
WHERE "core_person"."slug" = some-name

0 个答案:

没有答案