Reverse Strings in Django Admin

I have 2 models as follows. Now I need to embed Model A on the Model B 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 it possible ??? If yes, please let me know ..

+4
source share
2 answers

No, because A must have a ForeignKey for B to be used as Inline. Otherwise, how would the connection be recorded after saving the built-in A?

+3
source

You cannot do this, as Timmy O'Mahoney said. But you can make B inline in A if you want. Or maybe you can manipulate how django displays 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 relationships?

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) 
+1
source

Source: https://habr.com/ru/post/1383930/


All Articles