Django admin: reverse select foreign keys
I want to add pre-existing foreignkey items from the parent's admin. I have a "Bundle" model to hold "Product" items; many-to-one/foreignkey:
models.py
class Bundle(models.Model):
title = models.CharField(max_length=300)
class Product(models.Model):
title = models.CharField(max_length=300)
bundle = models.ForeignKey(
'Bundle',
on_delete=models.CASCADE,
null=True,
blank=True,
)
Below, I used StackedInline but this is for creating new products with a form:
admin.py
class ProductInline(admin.StackedInline):
model = Product
@admin.register(Bundle)
class BundleAdmin(admin.ModelAdmin):
inlines = [
ProductInline,
]
Instead, I want to repeatedly add existing products from a dropdown/search in the Bundle section of admin. So, I make a Bundle and then add a series of Products from a dropdown / with a search.
Thanks in advance.
For you requirement, you can use ManyToManyField
in Bundle
model instead of ForeignKey
in Product
model.
Check below code.
class Bundle(models.Model):
title = models.CharField(max_length=255)
product = models.ManyToManyField('Product')
class Product(models.Model):
title = models.CharField(max_length=255)
Then you can register admin interfaces:
admin.site.register(Bundle)
admin.site.register(Product)
Then you can add series of Product
from a dropdown/search.