Home > Mobile >  Django Subquery many values
Django Subquery many values

Time:02-15

class Category(models.Model):
    name = models.CharField(max_length=100)
    date = models.DateTimeField(auto_now=True)


class Hero(models.Model):
    name = models.CharField(max_length=100)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

I want Categoty model name, data, id

In cookbook , I wrote the code as above.

hero_qs = Hero.objects.filter(
    category=OuterRef("pk")
).order_by("-benevolence_factor")

Category.objects.all().annotate(
    most_benevolent_hero=Subquery(
    hero_qs.values('name')[:1]
    )
)

It seems that only one value can be entered in hero_qs.values('name')

Is it possible to get name, data, id with one annotate?

CodePudding user response:

You can try Concatenating the fields if you really want to use a single annotation

from django.db.models import Subquery, OuterRef, CharField, Value as V
from django.db.models.functions import Concat

hero_qs = Hero.objects.filter(
    category=OuterRef("pk")
).order_by("-benevolence_factor").annotate(
    details=Concat('name', V(','), 'id', output_field=CharField())
)

Category.objects.all().annotate(
    most_benevolent_hero=Subquery(
    hero_qs.values('details')[:1]
    )
)

Then you can use string interpolation to separate that data out which is a relatively inexpensive operation

name, id = category.most_benevolent_hero.split(',')

  • Related