Editing model ForeignKey as inline in Django admin

2019-06-11 11:00发布

Let's imagine that we have the following Django sample models:

class A(models.Model):
    title = model.CharField(max_length=64)
    b = models.ForeignKey(B, blank=True, null=True)


class B(models.Model):
    name = models.CharField(max_length=64)
    age = models.IntegerField()

In the Django administration, field A.b is going to be represented as a dropdown widget with controls for adding new B instance, editing it and deleting.

I would like to show the B model similar to the way inlines are shown. However, to show inlines we need a foreign key relation from B.a to A. And I do not want to introduce such relation.

Is it possible to represent B in the A model admin page, as an inline?

2条回答
狗以群分
2楼-- · 2019-06-11 11:12

Check out this tool - https://djangosnippets.org/snippets/2032/

A module that implements "reverse inlines" for this use case.

查看更多
我只想做你的唯一
3楼-- · 2019-06-11 11:38

If you want to know which B model are linked to concrete A model (reverse query), you can do:

b = B.objects.get(id=any_id)
a = b.a_set.all()

Then you can manage it, as you wish.

查看更多
登录 后发表回答