问题
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?
回答1:
Check out this tool - https://djangosnippets.org/snippets/2032/
A module that implements "reverse inlines" for this use case.
回答2:
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.
来源:https://stackoverflow.com/questions/35248336/editing-model-foreignkey-as-inline-in-django-administration