To add ModelForm for Many-to-Many fields with Python Django, we can add an intermediary table into our database that has the many to many relationships.
For instance, we write
class Pizza(models.Model):
name = models.CharField(max_length=50)
class Topping(models.Model):
name = models.CharField(max_length=50)
ison = models.ManyToManyField(Pizza, through='PizzaTopping')
class PizzaTopping(models.Model):
pizza = models.ForeignKey(Pizza)
topping = models.ForeignKey(Topping)
to add the PizzaTopping
model that has the pizza
and topping
fields that references Pizza
and Topping
.
Then in admin.py, we add
class PizzaToppingInline(admin.TabularInline):
model = PizzaTopping
class PizzaAdmin(admin.ModelAdmin):
inlines = [PizzaToppingInline,]
class ToppingAdmin(admin.ModelAdmin):
inlines = [PizzaToppingInline,]
admin.site.register(Pizza, PizzaAdmin)
admin.site.register(Topping, ToppingAdmin)
to create the PizzaToppingInline
class that has model
set to PizzaTopping
to let us modify PizzaTopping
from PizzaAdmin
and ToppingAdmin
.