I'm fairly new to Django, but wondering how to get one seemingly obvious thing to work in my model definitions.
For a model "Product" I want to be able to add any number of links, so I made a more or less generic "Link" model with a display name field and a URL field. In Product I add this as ManyToManyField
with the respective Link model.
This works like intended in the admin view in that I can add any number of links and do so inline. However, I only want the admin view to list existing links of this product, let the user delete them, and let the user add new ones. What I do not want is for the inline link field to display all other product’s links.
Am I confused with the Field Type or overall approach, or how can I get this to work? I was wondering if the through options is the way to do this, or if this is merely something you should do in the admin forms and not on model level?
Edit: Code sample added below
Edit: Code sample updated with formfield_for_manytomany
In models.py
:
class Product(models.Model):
name = models.CharField(max_length=256)
links = models.ManyToManyField('Link', related_name='links', default=None, blank=True, null=True)
class Link(models.Model):
name = models.CharField(max_length=256)
url = models.URLField(max_length=256)
In admin.py
:
class LinksInline(admin.StackedInline):
model = Link
class ProductAdmin(admin.ModelAdmin):
inlines = [LinksInline]
def formfield_for_manytomany(self, db_field, request, **kwargs):
kwargs["queryset"] = Link.objects.filter(font_id=self.object_id)
return super().formfield_for_manytomany(db_field, request, **kwargs)
admin.site.register(Link)
admin.site.register(Product)