add fields to model from another one related with OneToOneField or ForeignKey relation

爷,独闯天下 提交于 2019-12-08 13:17:06

问题


i am new to django and i am using the 1.11 version
i have several models some related with foreign keys and some with oneToOne relation.
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. 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
in AdminAdmin ie: the admin model i would like to add the user's fields in the form showing in the admin template

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'."


回答1:


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. E.g. you can access the model A's name field from related models with:

B

'fk__name'

C

'oto__name'



来源:https://stackoverflow.com/questions/45786983/add-fields-to-model-from-another-one-related-with-onetoonefield-or-foreignkey-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!