我有三个模型,如Store,ProductsArea和Item。商店可以有很多ProductsArea,而ProductsArea可以有很多商品。
#models.py
class Store(models.Model):
name = models.CharField(max_length=64, unique=True)
description = models.TextField(null=True, blank=True)
class ProductArea(models.Model):
store = models.ForeignKey(Store, related_name='productarea', on_delete=models.CASCADE)
name = models.CharField(max_length=64,verbose_name=_('Name'))
class Item(models.Model):
product_area = models.ForeignKey(ProductArea, related_name='items', on_delete=models.CASCADE, verbose_name='Menu')
name = models.CharField(max_length=64, verbose_name=_('Name'))
price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name=_('Price'))
在我看来,我正在使用CBV,我希望返回包含相同ProductArea的所有项目,单击确定的ProductArea中的ListItems,使用FK,它们从ProductArea获取所有项目。对于Store中的ProductArea也是如此。
Store - Clothes Store
Product Area - Shirts, Pants
Item - Shirt Yellow(PA.Shirts), Shirt Blue(PA.Shirts)
Item - Pant Black(PA.Pants), Pants Red(PA.Pants)
如果点击Shirts
,我想返回一个包含Shirt Yellow
和Shirt Blue
的列表。
我在我的观点中试过这个:
def get_queryset(self):
product_area_id = ProductArea.objects.get(id)
product_area = ProductArea.objects.get(pk=product_area_id)
items_in_productarea = Item.objects.filter(product_area=product_area)
return items_in_productarea
但是没有用,有builtin_function_or_method' object is not iterable
任何人都可以帮助我吗?非常感谢朋友们。
问题是你使用id
[Python-doc]。现在id
是一个内置的Python函数:它将所有对象映射到一个唯一的数字。例如,它用于检查两个变量是否引用同一个对象。 id
的细节在这里并不重要,重点是id
不是URL中的id
。
您需要从某处获取id
,例如它可以是URL的一部分。我们可以在urls.py
中指定它:
# app/urls.py
from django.urls import path
urlpatterns = [
path('items/<int:area_id>/', MyItemView.as_view(), name='my_item_view')
]
我建议在这里使用area_id
而不是id
,否则它可能会给出(假)它是id
s的Item
的印象。
然后我们可以使用self.kwargs
处理URL参数:
# app/views.py
from django.views.generic.list import ListView
from app.models import Item
class MyItemView(ListView):
# ...
def get_queryset(self):
return Item.objects.filter(product_area__id=self.kwargs['area_id'])
如果你获取localhost:8000/items/123
(使用123
ProductArea
的想法,如果例如app/urls.py
包含在非空路径中,则URL可以是不同的),您将获得属于此Item
的ProductArea
s列表。