Optional additional data on ManyToManyField
I have a ManyToManyField in Django, and I want to save additional information fo开发者_高级运维r the relation. What I am doing is
class Speaker(models.Model):
name = models.CharField(max_length=50)
title = models.CharField(max_length=100, blank=True)
description = models.TextField(blank=True)
class Event(models.Model):
title = models.CharField(max_length=120)
speakers = models.ManyToManyField(Speaker, blank=True, null=True, through='Role')
class Role(models.Model):
speaker = models.ForeignKey(Speaker)
event = models.ForeignKey(Event)
role = models.CharField(max_length=50, blank=True)
As per documentation, this prevents Django from doing some automatic stuff. What is particularly annoying is that it makes the Speaker list not available when creating an Event in the admin.
I realize that in general Django does not know what to put in the Role.role
field. But that is optional (blank=True
). I would expect that
- either Django recognizes that Role has only optional fields and lets me use the many to many relation as usual (creating the fields with an empty default), or
- Django admin lets me add Speakers to a newly created event, and for each such Speaker it asks for the additional information (the value of
Role.role
).
The second possibility would be more useful and more general than the first. Still Django admin does none of the two: instead the speakers field is removed from the Event.
Is there a way to make Django admin behave as described above?
The solution lies in this answer. Briefly, one should use InlineModelAdmin
, as documented here. This realizes exactly the second behaviour I described.
精彩评论