简体   繁体   中英

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. Is there any way to do this?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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