Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django queryset select_related . values() rename key

Using python3.4 django 2.0.2

models.py

class Userinfo(models.Model):

    useruid = models.BigAutoField(db_column='UserUID', primary_key=True)

    useremail = models.CharField(
            db_column='UserEmail', unique=True, max_length=100)
    userpassword = models.CharField(db_column='UserPassword', max_length=128)

    passwordsalt = models.CharField(db_column='PasswordSalt', max_length=128)
    userstatus = models.IntegerField(db_column='UserStatus', default=0)
    username = models.CharField(
        db_column='UserName', max_length=100, default=0)
    class Meta:
        managed = False
        db_table = 'userinfo'

class Postinfo(models.model):
    postuid = models.BigAutoField(db_column='PostUID', primary_key=True)
    content = content = models.TextField(db_column='Content')
    useruid = models.ForeignKey(
    Userinfo, db_column='UserUID', on_delete=models.CASCADE)

    class Meta:
         managed = False
         db_table = 'postinfo'

queryset

postquery = models.Postinfo.objects.all().select_related("useruid").order_by(
                '-postuid')

postquery is

<QuerySet [{'content': 'test','postuid': 1, 'useruid_id': 1},OtherPosts...>

and

userinfoquery = postquery.values("useruid_id__username","useruid_id__userstatus","useruid_id")

userinfoquery is

 <QuerySet [{'useruid_id__username': 'firstuser','useruid_id__userstatus': 0, 'useruid_id': 1},OtherUsers...>

i want useruid_id__username - > username

useruid_id__userstatus -> userstatus

useruid_id - > useruid

i tried this

userinfoquery = postquery.values(
                useruid="useruid_id", username="useruid_id__username", userstatus="useruid_id__userstatus")

this code raise exception

QuerySet.annotate() received non-expression(s): useruid_id, useruid_id__uesrname, useruid_id__userstatus.

how can remove useruid_id__

like image 412
Adam Avatar asked May 14 '18 06:05

Adam


2 Answers

Since Django 1.11 you can use expression with values(), check release notes. So you need to add F expression to your query:

from django.db.models import F
userinfoquery = postquery.values(
                useruid=F("useruid_id"), username=F("useruid_id__username"), userstatus=F("useruid_id__userstatus"))
like image 168
neverwalkaloner Avatar answered Sep 23 '22 16:09

neverwalkaloner


HI you can use annotate function

from django.db.models import F

Postinfo.objects.annotate(renamed_value=F('useruid_id__username')).values('renamed_value')
like image 28
Robert Avatar answered Sep 22 '22 16:09

Robert