【问题标题】:How to properly use filter method with foreign key in django details view with multiple models如何在具有多个模型的 django 详细信息视图中正确使用带有外键的过滤器方法
【发布时间】:2020-08-31 19:50:25
【问题描述】:

我有两个模型,一个模型用于存储博客文章,另一个模型用于获取评级和 cmets。下面是我的两个模型

# Models Code
class Products(models.Model):
    name = models.CharField(max_length=50)
    img = models.ImageField(upload_to='productImage')
    CATEGORY = (
        ('Snacks','Snacks'),
        ('Juice','Juice'),
    )
    category = models.CharField(max_length=50, choices=CATEGORY)
    description = models.TextField()
    price = models.FloatField()
    review = models.TextField()

# Rating Model
class Rating(models.Model):
    product = models.ForeignKey(Products, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)])
    comment = models.TextField()


#Views Code
class ProductListView(ListView):
    model = Products
    template_name = 'products.html'
    context_object_name ='Products'

class ProductDetailView(DetailView):
    model = Products

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super().get_context_data(**kwargs)
        context['Rating'] = Rating.objects.filter(self.product_id) # How can i get the comments only for that specific product?
        return context

详细查看我应该如何过滤以仅获取该特定产品的 cmets?

【问题讨论】:

    标签: django django-models django-rest-framework django-views django-templates


    【解决方案1】:

    不需要在ProductDetailView中写单独的上下文,你可以在模板中这样做

    {% for rate in object.rating_set.all %}
     {{ rate.comment }}
    {% endfor %}
    

    【讨论】:

    • 谢谢,它成功了,但你能告诉我它是如何工作的吗,因为我的 Product 表中没有任何 rating_set 属性?
    • 即反向查找FK,小写字母_set的子模型名称,如果您有相关名称则可以直接调用该名称而无需_set
    猜你喜欢
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多