Django: How to write an alias in a query set

How can I write an alias for a column name in a Django query set. It would be useful for unions in the style of combining two related fields with the same external model (for example).

for example in mysql:

select m as n, b as a from xyz 

how can i do this in a django query set?

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

Any help really appreciate this.

+4
source share
5 answers

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

To this end, and inspired by the Alex ticket, I just posted a patch that adds this feature. Hope you find this helpful!

+8
source

Your reason in the comment does not make sense. Each field in the model has its own column in the database, and there is never the danger of mixing them. You can, of course, specify a column name in the field other than the field name:

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

but I don’t know if this will help you, because I still don’t know what the problem is.

+3
source

You can annotate the fields as you wish with the expression F :

 from django.db.models import F models.Table.objects.all().values('m', 'b').annotate(n=F('m'), a=F('b')) 
+2
source

I suppose this is not possible, so I raised a ticket for the added function, I think there is some merit in the ability to do this. For more information see Ticket.

https://code.djangoproject.com/ticket/16735

+1
source

I really can’t understand what you are trying to do, but it looks like you are looking for an extra query method. This for most purposes acts like an AS in sql.

0
source

All Articles