如何在同一视图中显示来自两个不同型号的字段

如何在同一视图中显示来自两个不同型号的字段

本文介绍了Django Admin:如何在同一视图中显示来自两个不同型号的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站利用Django的用户验证用户模型和自定义UserProfile模型来存储一些其他数据(生日等)。有没有办法在Django管理员中创建一个视图,将用户和UserProfile模型中的字段编织在一起?

My site makes use of Django's User Authentication User model and a custom UserProfile model to store some additional data (birthday, etc.). Is there a way to create a view in Django admin that weaves together fields from both the User and UserProfile models?

我怀疑这个代码片段不甚接近,但是也许这将有助于说明我正在做的事情:

I suspect that this code snippet is not even close, but maybe it will help illustrate what I'm trying to do:

from django.contrib import admin
from django.contrib.auth.models import User
from userprofile.models import UserProfile


class UserProfileAdmin(admin.ModelAdmin):
    list_display = ('name', 'gender', 'User.email') #user.email creates the error - tried some variations here, but no luck.

admin.site.register(UserProfile, UserProfileAdmin)

错误消息:

最终,我试图创建一个管理视图,具有第一个&来自UserProfile的姓氏和用户的电子邮件。

Ultimately, I'm trying to create an admin view that has first & last name from UserProfile and email from User.

推荐答案

显示用户电子邮件,您需要在 UserProfile UserProfileAdmin 返回电子邮件

for displaying user email you need to have a method on UserProfile or UserProfileAdmin that returns the email

在UserProfile

on UserProfile

def user_email(self):
    return self.user.email

或UserProfileAdmin

or on UserProfileAdmin

def user_email(self, instance):
    return instance.user.email

然后更改您的 list_display to

then change your list_display to

list_display = ('name', 'gender', 'user_email')

这篇关于Django Admin:如何在同一视图中显示来自两个不同型号的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:11