[Answered ]-ManyToManyField not saving correctly

1👍

You have two links, a ForeignKey and a ManyToManyField, likely that makes not much sense. While not fundamentally impossible, often there is either a ForeignKey from one model to another, or an ManyToManyField in between. The ModelAdmin here picked the product foreign key, since that is the only thing, an InlineModelAdmin can use "out of the box".

This is not trivial if you want to use a ManyToManyField. But if you define a ManyToManyField, you create a (hidden) model. Indeed, one with two ForeignKeys: in this case one that points to a Product and one to an ItemOption. So we can work with that model as is specified in the working with many-to-many models section of the documentation:

class ItemOptionThroughInline(admin.TabularInline):
    model = Product.item_option.through
    extra = 1
    can_delete = True


class ProductAdmin(admin.ModelAdmin):
    list_display = ('title', 'price', 'product_type')
    list_filter = ('product_type', 'brand')
    exclude = ('item_option',)
    inlines = [ItemOptionThroughInline]

this will however only make pointing to already existing ItemOptions convenient. It would also be weird to have an ItemOption form anyway: it means that if you change an ItemOption that is linked on two Products, through the edit page of one product, then the change is thus also reflected in the edit page of the other product. So likely, you simply wanted a ForeignKey in the ItemOption model, and make options, specific to a (single) Product.

Leave a comment