开发者

Show models.ManyToManyField as inline, with the same form as models.ForeignKey inline

I have a model similar to the following (simplified):

models.py

class Sample(models.Model):  
    name=models.CharField(max_length=200)  

class Action(models.Model):  
    samples=models.ManyToManyField(Sample)
    title=models.CharField(max_length=200)  
    description=models.TextField()  

Now, if Action.samples would have been a ForeignKey instead of a ManyToManyField, when I display Action as a TabularInline in Sample in the Django Admin, I would get a number of rows, each containing a nice form to edit or add another Action. However; when I display the above as an inline using the following:

class ActionInline(admin.TabularInline):
    model=Action.samples.through

I get a select box listing all available actions, and not a nifty form to create a new Action.

My question is really: How do I display the ManyToMany relation as an inline with a form to input information as described?

In prin开发者_如何学Cciple it should be possible since, from the Sample's point of view, the situation is identical in both cases; Each Sample has a list of Actions regardless if the relation is a ForeignKey or a ManyToManyRelation. Also; Through the Sample admin page, I never want to choose from existing Actions, only create new or edit old ones.


I see your point but think of a case where you might need to use custom through model (table). In that case the admin inline form would include the fields for that intermediate model since thats the model you asked the admin to create the form for.

e.g.

class Person(models.Model):
    name = models.CharField(max_length=128)

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

The admin should display the form for the Memebership model cause thats the model the editable instance is related to. In your case the through model contains only the 2 foreign keys (1 for the Action model and 1 for the Sample) ands thats why only the list of actions appear.

You could do what you are asking for if django admin supported nested inlines (there is an open ticket about that).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜