EngineerCamp EngineerCamp - 11 days ago 4
Python Question

Add Django ForeignKey as drop down selection on admin page

I want to be able to create a model

TestCase
which has a
products
field which is a ForeignKey to antoher model
Product
. I want to be able to create a new
Product
using the Admin page and then when I create a
TestCase
I want to be able to select from
Product
s I have already created. A dropbox would be ideal. This is what I have tried:

models.py

class TestCase(TestBase):

def __str__(self):
return self.title


class Product(models.Model):
products = models.ForeignKey(TestCase, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=200, default='')

def __str__(self):
return self.name


admin.py

class ProductInline(admin.TabularInline):

model = Product


class TestCaseAdmin(admin.ModelAdmin):

inlines = [ProductInline]

admin.site.register(TestCase, TestCaseAdmin)


Adding a new
TestCase
on the admin page now has fields to create a Product but I want to select from already created
Products
instead?

Thanks in advance.

Answer

You have the wrong model structure. If you want to be able to choose from a list of already-existing Products in your TestCase, and a Product can belong to multiple TestCases, you need a ManyToManyField which lives on TestCase.

Comments