Zygro
Zygro

Reputation: 7119

How to create inline for a model with common referenced model in Django admin?

So I have these kind of models:

def Profile(models.Model):
    user = OneToOneField(User, primary_key=True)

def OtherProfile(models.Model):
    user = OneToOneField(User, primary_key=True)

def Item(models.Model):
    user = ForeignKey(User)

And I want to have ItemInline in ProfileAdmin (and similarly in OtherProfileAdmin). I tried doing it like this:

class ItemInline(admin.TabularInLine):
    model = Item

@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
    inlines = [ItemInline]

However, this shows me this error:

<class 'app.admin.ItemInline'>: (admin.E202) 'api.Item' has no ForeignKey to 'api.Profile'.

How do I put the ItemInline into ProfileAdmin?

I can't put ForeignKey(Profile) into the Item, because then I would not be able to access Item from OtherProfile.

Upvotes: 0

Views: 183

Answers (1)

joe513
joe513

Reputation: 96

To be able to add inline you have to create a FK (Foreign Key) to it.

models.py

def Profile(models.Model):
    user = ForeignKey(User)

def Item(models.Model):
    user = ForeignKey(Profile)

admin.py

class ItemInline(admin.TabularInLine):
    model = Item

@admin.register(Profile)
class ProfileAdmin(admin.ModelAdmin):
    inlines = [ItemInline]

Upvotes: 1

Related Questions