[英]Django model with multiple foreign keys
我想創建一個按區域、需求和產品類別分類的產品列表。 我創建了 3 個相互回復的獨立模型,因此用戶可以輕松添加類別並從下拉列表區域和需要中進行選擇。
目前,我有 3 個區域,在每個區域下我都有需求。 我想要的是呈現Area
模型中的項目列表, Area
模型中的每個項目下Need
模型中的所有項目以及Need
模型中的每個項目下Product
模型中的所有項目(僅標題)。
此處未使用ProductCategory
模型,但我在其他地方需要它,它是產品和區域/需求之間的連接器。 添加新產品時,定義類別並從下拉列表中選擇它們要容易得多。
我需要創建一個循環來顯示類似上面的內容。 我知道這行不通,但我想展示邏輯。
我的問題是渲染這樣的東西的最佳方法是什么?
如何在我的班級和我的 html 中獲取category_area
和category_need
?
模型.py
class Area(models.Model):
title = models.CharField(max_length=75, blank=False)
body = models.CharField(max_length=150, default='-', blank=False)
publish = models.DateTimeField('publish', default=timezone.now)
class Need(models.Model):
title = models.CharField(max_length=75, blank=False, null=False, help_text='max 75 characters')
body = models.CharField(max_length=150, default='-', blank=False)
publish = models.DateTimeField(default=timezone.now)
need_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='need_area')
class ProductCategory(models.Model):
title = models.CharField(max_length=400, blank=False, null=False, help_text='max 400 characters')
body = models.TextField(default='-')
publish = models.DateTimeField('publish', default=timezone.now)
category_area = models.ForeignKey(Area, on_delete=models.CASCADE, related_name='category_area', null=True)
category_need = models.ForeignKey(Need, on_delete=models.CASCADE, related_name='category_need', null=True)
class Product(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=400, blank=False)
category = models.ForeignKey(ProductCategory, on_delete = models.CASCADE, blank=True, related_name='products')
def get_absolute_url(self):
return reverse("product", kwargs={'slug': self.slug})
視圖.py
class SearchProducts(LoginRequiredMixin, ListView):
login_url = 'login'
redirect_field_name = 'login'
template_name = 'hubble/search/manual_search.html'
model = Product
queryset = Product.objects.all()
def get_context_data(self, **kwargs):
context = super(SearchProducts, self).get_context_data(**kwargs)
product_results = ProductCategory.objects.prefetch_related("products").all()
context['product_results'] = product_results
return context
product_search.html
<div>
{% for area in product_results %}
<h6>{{area.title}}</h6>
{% endfor %}
</div>
您可以prefetch_related
所有向后關系並進行類似於此的迭代:
areas = Area.objects.prefetch_related('need_area__category_need__products')
for area in areas:
# iterate through each instance of Area
for need in area.need_area.all():
# iterate through each instance of Need for the given area
for product_category in need.category_need.all():
# iterate through each instance of ProductCategory for the given need
for product in product_category.products.all():
# iterate through each instance of product for the given product category
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.