簡體   English   中英

Django Queryset-從第三模型檢索數據的問題

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

我想從產品具有的每個審閱的個人檔案模型中獲取“ profilephoto”,但這需要審閱模型profile_id,而該個人檔案已經是上下文的一部分。 有什么辦法嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM