使用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'
查询集
postquery = models.Postinfo.objects.all().select_related("useruid").order_by(
'-postuid')
postquery是
<QuerySet [{'content': 'test','postuid': 1, 'useruid_id': 1},OtherPosts...>
和
userinfoquery = postquery.values("useruid_id__username","useruid_id__userstatus","useruid_id")
userinfoquery是
<QuerySet [{'useruid_id__username': 'firstuser','useruid_id__userstatus': 0, 'useruid_id': 1},OtherUsers...>
我想要useruid_id__username - &gt;用户名
useruid_id__userstatus - &gt; userstatus
useruid_id - &gt; useruid
我试过这个
userinfoquery = postquery.values(
useruid="useruid_id", username="useruid_id__username", userstatus="useruid_id__userstatus")
此代码引发异常
QuerySet.annotate() received non-expression(s): useruid_id, useruid_id__uesrname, useruid_id__userstatus.
如何删除useruid_id__
答案 0 :(得分:2)
自Django 1.11起,您可以将表达式与values()
一起使用,请检查release notes。因此,您需要在查询中添加F
表达式:
from django.db.models import F
userinfoquery = postquery.values(
useruid=F("useruid_id"), username=F("useruid_id__username"), userstatus=F("useruid_id__userstatus"))
答案 1 :(得分:2)
您可以使用注释功能
from django.db.models import F
Postinfo.objects.annotate(renamed_value=F('useruid_id__username')).values('renamed_value')