How to add a fixed value field to the queryset of django?

  1. suppose I have the following code:
from django.contrib.auth.models import User

us = User.objects.all()

-sharp  idis_active
v1 = us.values("id", "is_active")

-sharp ( User ): other="hehe"
-sharp [{"id": 1, "is_active": True, "other": "hehe"}, ...]
v1 = us.values("id", "is_active", other="hehe")  -sharp 

I hope someone who knows can help me.

Mar.28,2021

I think this is a XY problem .
the effect you want to achieve should not be achieved in this way.
if you can state your purpose, I'm sure a lot of people can help you solve it.

I am also interested in whether it can be realized or not. I am studying masturbation skills.

update:
I looked at the source code of Django and found no elegant solution, at least nothing more convenient than a direct loop.
GG.

you'd better add it in a loop.


annotate use annotations


you can do this with annotate, like this
.annotate (mycolumn=Value ('xxx', output_field=models.CharField ()


django orm does not provide this feature, iterate through v1 and add it one by one.


coincidentally, when I was looking up another question recently, I found a knowledge point related to this. I think you can use sql tricks to do this.
post the code I ran in my own shell

.
from useraccount.models import User
sql = ''' select id, is_active,'haha' as other from useraccount_user limit 5'''
us = User.objects.raw(sql)
for u in us:
    print u.id, u.is_active,u.other
    
1 True haha
2 True haha
3 True haha
4 True haha
5 True haha
    

it is important to note that the primary key must be filtered when using the raw function select, otherwise it will explode when actually accessing the field

InvalidQuery: Raw query must include the primary key 

annotate is fine. I've come across the need to add a field to the query set, which is calculated by other fields because of the need for sorting. And mysql also has syntax support.


Author.objects.create (name= "WeizhongTu", email= "tuweizhong@163.com")

Menu