#Annotating foreign key and get related object

5 messages · Page 1 of 1 (latest)

charred kestrel
#

Not sure if it's possible or not but can the ORM resolve a related object on annotations of id?

Table definitions

Table Foo:
  id

Table Bar
  id
queryset = Foo.objects.annotate(
  bar_id=Subquery(Bar.objects.values('id')[:1])  
)

queryset[0].bar.id # Like so

I'm sure the given snippet of code doesn't work. I'm asking if there's a way to do that other than looping through the queryset and getting the object itself.

autumn monolith
#

No, it's not possible. What about defining a relationship between Foo and Bar?

sleek moat
modest vigil
#

How do I give you a fist bump for this, lol.

Actually worked really well for me and what I needed to do. Thanks @sleek moat

sleek moat
#

You actually fist bump @versed flax! He's the author