Reputation: 5
I am trying to customize the Django Interface. I have a CategoryAdmin(admin.ModelAdmin) which has a foreignkey to self, every Category can have SubCategories from the same table.
Every category which has subcategory will be shown as inlines. Basically on the main Categories queryset I want to show those who's Parent = 0 so I overrided get_queryet to this:
def get_queryset(self, request):
if request.user.is_superuser:
qs = super(CategoryAdmin, self).get_queryset(request)
return qs
company = CompanyUsers.objects.filter(UserId = request.user.id) #not relevant
companyid = company.values_list('CompanyId', flat=True) #not relevant
qs = Category.objects.filter(CompanyId = companyid, Parent = 0)
return qs
Now when a user picks one of the Categories, the inlines are NOT filtered by that Parent = 0 but when clicking to change them I got the error:
"Category object with primary key 'x' does not exist"
Any Ideas on how to filter only on the main Categories queryset?
Note: when removing the "Parent = 0" the error disappears.
Note 2: Could be useful to know which instance was clicked. I know it's possible by overriding get_formset but unfortunately get_queryset is called before get_formset :(
Thanks alot.
Upvotes: 0
Views: 373
Reputation: 51
As parent refers to Category objects, why use 0 and not None instead? Parent must be an object not an integer.
In your Category Class declare parent as:
parent = models.ForeignKey(User, null=True, blank=True, default = None)
Only children categories will have a parent relationship, if a Category is parent then parent will be None. Then, when you want to get parent categories you will filter your query like:
Category.objects.filter(companyId = companyid, parent = None)
Also, parent will be a Category object not an integer.
Upvotes: 1