简体   繁体   English

Django Queryset-从第三模型检索数据的问题

[英]Django Queryset - Issue with retrieving data from 3rd model

I want to get the 'profilephoto' from the Profile model for each Review that a Product has but that requires the Review models profile_id which is already apart of a context. 我想从产品具有的每个审阅的个人档案模型中获取“ profilephoto”,但这需要审阅模型profile_id,而该个人档案已经是上下文的一部分。 Is there any way to do this? 有什么办法吗?

models.py models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE)
    profilephoto = models.ImageField(default='profiles/default_profile.jpg', upload_to='profiles')

class Product(models.Model):
    name = models.CharField(max_length=100)
    brand = models.CharField(max_length=100)
    cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00)
    category = models.CharField(max_length=100)
    releasedate = models.DateField()
    description = models.TextField()
    productphoto = models.ImageField(default='products/default_product.jpg', upload_to='products')

class Review(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    rating = models.PositiveSmallIntegerField(default=1, validators = [MinValueValidator(1), MaxValueValidator(5)])
    reviewtext = models.TextField()

views.py views.py

class ProductDetailView(TemplateView):
    # template_name = 'reviewApp/test.html'
    template_name = 'reviewApp/product_detail.html'
    def get_context_data(self, **kwargs):
        prod = self.kwargs['pk']
        context = super(ProductDetailView, self).get_context_data(**kwargs)
        context['Products'] = Product.objects.filter(id=prod)
        context['Reviews'] = Review.objects.filter(product=prod)
        prof = Review.objects.only('profile_id')
        context['Profiles'] = Profile.objects.filter(id__in=prof)
        return context
class ProductDetailView(TemplateView):
# template_name = 'reviewApp/test.html'
template_name = 'reviewApp/product_detail.html'
def get_context_data(self, **kwargs):
    prod = self.kwargs['pk']
    context = super(ProductDetailView, self).get_context_data(**kwargs)
    context['Product'] = Product.objects.get(id=prod)
    context['Reviews'] = Review.objects.filter(product_id=prod)
    profile_ids = Review.objects.values_list('profile_id', flat=True)
    context['Profiles'] = Profile.objects.filter(id__in=profile_ids)
    return context

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM