Editing model ForeignKey as inline in Django administration?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-23 05:01:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!