9

I have 2 models as follows. Now I need to inline Model A on Model B's page.

models.py

class A(models.Model):
    name = models.CharField(max_length=50)

class B(models.Model):
    name = models.CharField(max_length=50)
    a = models.ForeignKey(A)

admin.py

class A_Inline(admin.TabularInline):  
    model = A

class B_Admin(admin.ModelAdmin): 
    inlines = [A_Inline]

is that possible?? If yes please let me know..

Gathole
  • 892
  • 1
  • 13
  • 24

3 Answers3

1

You cannot do it as told by timmy O'Mahony. But you can make B inline in A if you want. Or maybe you can manipulate how django display it in

def unicode(self):

models.py

class A(models.Model):
    name = models.CharField(max_length=50)
    def __unicode__(self):
        return self.name

class B(models.Model):
    name = models.CharField(max_length=50)
    a = models.ForeignKey(A)

admin.py

class B_Inline(admin.TabularInline):  
    model = B
class A_Admin(admin.ModelAdmin):
    inlines = [
        B_Inline,
    ]
admin.site.register(A, A_Admin)
admin.site.register(B)

Or maybe you want to use many-to-many relationship?

models.py

class C(models.Model):
    name = models.CharField(max_length=50)
    def __unicode__(self):
        return self.name
class D(models.Model):
    name = models.CharField(max_length=50)
    cs = models.ManyToManyField(C)

admin.py

class C_Inline(admin.TabularInline):  
    model = D.cs.through
class D_Admin(admin.ModelAdmin):
    exclude = ("cs",)
    inlines = [
        C_Inline,
    ]
admin.site.register(C)
admin.site.register(D, D_Admin)
wanjijul
  • 252
  • 3
  • 7
1

Of course you can do this. Every relationship be it 1-1, m2m or FK will have a reverse accessor. (more on the FK reverse access here)

class A_Inline(admin.TabularInline):  
    model = A.b_set.through

class B_Admin(admin.ModelAdmin): 
    inlines = [A_Inline]
Jura Brazdil
  • 970
  • 7
  • 15
0

No, as A needs to have a ForeignKey to B to be used as an Inline. Otherwise how would the relationship be recorded once you save the inline A?

Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
  • 1
    If you really need it, and you are sure your relationships are correct (i.e. correct ForeignKeys etc.) you could overwrite the admin template for B's page and write in A's form manually. Alternatively you could create a generic foreign key between A and B, but this would alter the meaning of A (i.e. saying that A is allowed to be related to any unspecified object) – Timmy O'Mahony Dec 01 '11 at 11:56
  • 6
    What's wrong with: a.save(), b.a=a, b.save()? I have a model Config in which I want to store metadata for other models. I wanted to add one-to-one relationship to other models and inline Config and apparently it is not possible. Why can't django save the inline, set it on the relationship and save original model? – Ari Sep 22 '20 at 20:49