[英]add fields to model from another one related with OneToOneField or ForeignKey relation
i am new to django and i am using the 1.11 version 我是django的新手,正在使用1.11版本
i have several models some related with foreign keys and some with oneToOne relation. 我有几种模型与外键有关,有些与oneToOne关系。
for instance the user and profile models, i would like to add in the profile form fields from the user form 例如用户和个人资料模型,我想在用户表格中添加个人资料表格字段
how? 怎么样?
For the oneToOne, I have the an admin model with a oneToOne field related to the user model. 对于oneToOne,我有一个管理模型,其中有一个与用户模型相关的oneToOne字段。 but not just admin, i have several types of user (admin, writer, commetator, ...) each in a different model and when creating one type i also create its related user, so when i access the writer form in admin i create an admin but i also want to have user's model field so that i create both from the writer's form
但不仅仅是管理员,我有几种类型的用户(管理员,作家,通勤者...),每种用户使用不同的模型,并且在创建一种类型时,我也会创建其相关用户,因此当我在admin中访问作家表单时,我会创建一个管理员,但我也想拥有用户的模型字段,以便我从作者的表单创建
in AdminAdmin ie: the admin model i would like to add the user's fields in the form showing in the admin template 在AdminAdmin中,即:admin模型,我想以admin模板中显示的形式添加用户字段
from django.contrib import admin
from .models import User, Admin
class UserInline(admin.StackedInline):
model = User
fields = ['username', 'first_name', 'last_name']
class AdminAdmin(admin.ModelAdmin):
model = Admin
list_display = ['getUsername']
inlines = [UserInline]
def getUsername(self, obj):
return obj.user.username
getUsername.short_description = "Nom d'utilisateur"
admin.site.register(Admin, AdminAdmin)
this code generates the error ": (admin.E202) 'common.User' has no ForeignKey to 'common.Admin'." 此代码生成错误“:(admin.E202)'common.User'没有对'common.Admin'的ForeignKey。”
With this setup: 使用此设置:
Class A(models.Model):
# ...
nameField = models.CharField(max_length=100, ...)
# ...
pass
Class B(models.Model)
# ...
fk = models.ForeignKey(A)
# ...
Class C(models.Model):
# ...
oto = models.OneToOneKeyField(A)
You cann access a realted model's field with the ForeignKey
+ __
+ FieldName
. 您无法使用
ForeignKey
+ __
+ FieldName
访问实际模型的字段。 Eg you can access the model A's name field from related models with: 例如,您可以使用以下方法从相关模型中访问模型A的名称字段:
B 乙
'fk__name'
C C
'oto__name'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.