如何在 Python (Django) 中显示没有外键类名称的对象的值

该类Customer有一个类的外键User。我想返回此信息,但我不想在用户名、名字等之前显示 user__。


data = {"customers": list(p.values("id", "user__username", "user__first_name",

                                       "user__last_name", "user__email", "phone",

                                       "address", "balance"))}

我怎样才能得到这样的东西:


{

"customers": [

    {

        "id": 12,

        "username": "leon2",

        "first_name": "lee",

        "last_name": "michalson",

        "email": "hamed@example.com",

        "phone": "042-22334455",

        "address": "Tehran, No.1",

        "balance": 20000

    }


]

}


森栏
浏览 46回答 1
1回答

慕莱坞森

使用注释:from django.db.models import Ffor field in ('username', 'first_name', 'last_name', 'email'):    p = p.annotate(**{field: F('user__' + field)})data = {"customers": list(p.values("id", "username", "first_name",                                       "last_name", "email", "phone",                                       "address", "balance"))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python