The context is an inventory app of an e-commerce project. As expected, there's a Product model. In an attempt to normalize the DB schema, I have created these additional models:
- ProductType (ForeignKey relationship in Product)
- ProductSpecification (a FK in ProductType)
- ProductInventory (with a FK to Product)
- ProductSpecificationValue (FK to both ProductSpecification and ProductInventory)
I hope this makes sense - each ProductType has many Products, and also many Specifications.
ProductInventory (suggestions of a better name are welcome), with a FK to Product, is a model with SKU and quantity fields. And the fun part - it has a ManyToMany relationship to ProductSpecification, through ProductSpecificationValue.
Now the part where I am lost is adding this whole thing to Django Admin site.
I can create ProductTypes and Products without any problem, and a ProductTypeAdmin has an inline to add those specs:.
@ admin.register(ProductType)
class ProductTypeAdmin(admin.ModelAdmin):
inlines = [
ProductSpecificationInline,
]
The problem starts when I try to add a ProductInventory entity. Because it's associated with a given ProductType, I want to limit the choice of inlines to only those which are related to the same ProductType.
class ProductSpecificationValueInline(admin.TabularInline): model = ProductSpecificationValue
def get_formset(self, request, obj=None, **kwargs): # obj is always the current Product
print(f">>>>>>>>>>>>>>>>>>>>>> get_formset on PSVI")
print(f"obj: {obj}")
print(f"kwargs: {kwargs}")
fset = super().get_formset(request, obj, **kwargs)
assert fset is not None
print(f"fset dir: {dir(fset)}")
# qs = fset.get_queryset(self)
# print(f"qs: {qs}")
return fset
the print of 'dir(fset)' shows that 'get_queryset' function is available - but whe I try to call it, I get an error:
File "/home/devuser/.pyenv/versions/venv38/lib/python3.8/site-packages/django/forms/models.py", line 744, in get_queryset
'ProductSpecificationValueInline' object has no attribute 'queryset'
I know that I need a queryset attached to ProductSpecifications dropdown, so that I can filter the ProductSpecification objects by the ProductType, which is available on the 'obj'. But I guess I'm not overriding a correct method of the ModelAdmin (or it's subclass admin.TabularInline)? So for now I am stcu with all of Specs for all Types showing up.
Well, thank you for your time y'all; in case you want to see the admin.py/models.py, here they are
PS: this way of getting some queryset (not saying it's a right one), kinda "works":
qs = super().get_queryset(request)
, but that queryset comes empty