[Fixed]-Using annotate or extra to add field of foreignkey to queryset ? (equivalent of SQL "AS" ?)


I’ve used an F expression to achieve this sort of renaming before. Try this:

from django.db.models import F

qs2 = Offer.objects.select_related('subscription').annotate(monthly_fee=F('subscription__monthly_fee'))


OK, I found a way to do this.

qs2 = Offer.objects.select_related('subscription').extra(select={'monthly_fee':'mobile_subscription.monthly_fee'})

where ‘mobile’ is the name of the Django app. I didn’t realize that .extra DOES allow you to follow foreign keys but that you actually have to specify the actual database table and use SQL dot notation.

Is the above the actual correct way we are supposed to do it ? (i.e. dropping in raw SQL table names/fields)

I had been trying to use Django syntax such as .extra(select={'monthly_fee':'subscription__monthly_fee'}) which doesn’t work!

Leave a comment