外键django-数据库关系

ykejflvf  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(359)

我公司有一款针对香水的产品,该产品有不同的体积和价格。我需要为每个渲染体积和价格,但我得到“'function'对象没有属性'prices'”
有什么想法吗?我很感激你的建议
查看:

from django.shortcuts import render

from django.views.generic import View, TemplateView
from products.models import Perfume, Pricing

def getIndex(request):

    perfumes = Perfume.objects.all
    thePrice= perfumes.prices.all()

    return render(request, 'index.html', {'perfumes': perfumes, 'thePrice':thePrice})

模型

from django.conf import settings
from django.db import models
from django.utils import timezone

class Perfume(models.Model):

    genderChoice = (
        ('unisex','unisex'), ('male', 'male'), ('female', 'female'))

    name = models.CharField(max_length=50, default='')
    brand = models.CharField(max_length=40, default='')
    gender = models.CharField(max_length=7, choices=genderChoice, default='unisex')

    description = models.TextField()
    image = models.ImageField(upload_to='images/product_image')
    created = models.DateField()
    author =models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    active = models.BooleanField(default=False)
    show_for_consumer = models.BooleanField(default=False)

    def __str__(self):
        return self.name        

class Pricing(models.Model):
    product =models.ForeignKey(Perfume, on_delete=models.CASCADE,related_name='prices')

    price= models.DecimalField(max_digits=10, decimal_places=2)
    volume= models.DecimalField(max_digits=10, decimal_places=2)
    def __str__(self):
         return 'Perfume {} - Price{} - Volume {}'.format(self.product.name,self.price, self.volume)
fxnxkyjh

fxnxkyjh1#

首先,你需要纠正缺失的部分 () 在得到香水的时候

perfumes = Perfume.objects.all()

这个 thePrice = perfumes.prices.all() 不正确。你必须为每一款香水做这个,而不是一瓶 queryset 香水。
Perfume 以及 Pricing 有一对多的关系,你可以直接从每个香水示例获取价格。这样你只需要通过香水 queryset ```
def getIndex(request):
perfumes = Perfume.objects.all()
return render(request, 'index.html', {'perfumes': perfumes})

最后,在模板中,可以这样调用价格

{% for product in perfumes %}
...
{% for p in product.prices.all %}
{{p.volume}}ml - {{p.price}}$
...
{% endfor %}
{% endfor %}

相关问题