Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django : How to write alias in queryset

How can one write an alias for the column name in django query set. Would be useful for union-style combinations of two linked field to the same foreign model (for instance).

for example in mysql :

select m as n, b as a from xyz

how can i do this in django query set ?

models.Table.objects.all().values('m', 'b')

Any help really appreciate it.

like image 868
sush Avatar asked Jul 26 '11 17:07

sush


People also ask

What does QuerySet []> mean?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data. In this tutorial we will be querying data from the Members table.

What is annotate in Django QuerySet?

Appending the annotate() clause onto a QuerySet lets you add an attribute to each item in the QuerySet, like if you wanted to count the amount of articles in each category. However, sometimes you only want to count objects that match a certain condition, for example only counting articles that are published.

What is Select_related in Django?

Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects. The select_related method is for ForeignKey and OneToOne fields.


3 Answers

Your reason in the comment makes no sense. Each field in the model has its own column in the database, and there's never any danger of mixing them up. You can of course tell a field to use a column name that's different from the field name:

myfield = models.CharField(max_length=10, db_column='differentname')

but I don't know if that will help you, because I still don't know what your problem is.

like image 25
Daniel Roseman Avatar answered Sep 21 '22 17:09

Daniel Roseman


You can annotate the fields as you want, with the F expression:

from django.db.models import F

models.Table.objects.all().values('m', 'b').annotate(n=F('m'), a=F('b'))
like image 91
A K Avatar answered Sep 18 '22 17:09

A K


Although this could have been done before by using extra(select={'n':'m','a':'b'}), I agree that this really should have been a part of values() itself.

To that end, and inspired by Alex's ticket, I have just posted a patch that adds this feature. I hope you'll find it useful!

like image 26
Nate Avatar answered Sep 17 '22 17:09

Nate