【问题标题】:How to print values of model joined through foreign key in django?如何在 django 中打印通过外键连接的模型的值?
【发布时间】:2021-10-28 11:44:44
【问题描述】:

我有一个模型命名如下:

class Item(models.Model):
 title = models.CharField(max_length=100)
 price = models.FloatField()
 bargainprice = models.FloatField(default=0)
 discount_price = models.FloatField(blank=True, null=True)
 category = models.CharField(choices=CATEGORY_CHOICES, max_length=2)
 label = models.CharField(choices=LABEL_CHOICES, max_length=1)
 slug = models.SlugField()
 description = models.TextField()

 image = models.ImageField()

并有一个名为“product.html”的产品页面,显示当前产品信息,如图所示:the product page image

我通过如下视图获取 product.html 上的所有这些数据:

class ItemDetailView(DetailView):
model = Item
template_name = "product.html"

在 product.html 上,我通过语法获取数据:

         <span class="mr-1">
          <del>₹ {{ object.price }}</del>
        </span>
        <span>₹ {{ object.discount_price }}</span>

这是一个运行良好的故事直到那里没有问题**当我在下面创建这个讨价还价模型时问题就开始了**

class Bargain(models.Model):
    user = models.ForeignKey(
       settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
         )
    item = models.ForeignKey(
        Item,
        on_delete=models.CASCADE
        )
    bprice = models.FloatField()



    class Meta:
        constraints = [
            models.UniqueConstraint(
               fields=['item', 'user'], name='unique_user_item')
         ]

*让我解释一下这种讨价还价模式的目的。实际上这个模型是用来讨价还价的,它从用户那里获取输入价格,并更新为讨价还价模型,具有以下值用户、项目和“bprice”,即讨价还价后产品的新价格*

我已经成功地在模态中创建了一个对象“Bargain object (3)”,其值如图所示:image of modal values

**so what i need - if user have bargained the price product.html show the bargain price which is "bprice" in the Bargain modal instead of product price in Item modal** of the respective user**

为了实现这一点,我将 itemView 更改如下:

class ItemDetailView(DetailView):
    model = Item
    template_name = "product.html"
     
    def get_bargain(self, request):
      if request.user.is_authenticated():
         return Bargain.objects.filter(item=self.object, user=request.user).first()

在 product.html 上我正在这样做:&lt;h1&gt;This is the {{ view.get_bargain.bprice }}&lt;/h1&gt;

*但这没有给我任何东西* 更多信息 - 登录用户 admin

谁能建议我做错了什么或任何其他方法? 提前致谢。

【问题讨论】:

  • 我无法纠正错误是什么?

标签: python-3.x django django-models


【解决方案1】:

如果您的视图仅限于登录用户,您可以从LoginRequiredMixin 扩展您的视图。然后您可以指定上下文对象名称“item”,如下所示。

class ItemDetailView(LoginRequiredMixin, DetailView):
    model = Item
    template_name = "product.html"
    context_object_name = "item"
 
    def get_object(self, queryset=None):
          return get_object_or_404(self.model, pk=self.kwargs['pk'])

并且在您的模板中,您可以获得与此项目相关的所有便宜货。 就像。

{% if item.bargain %}
     <h1>This is the {{ item.bargain.first.bprice }}</h1>
{% else %}
     <h1> no bargain against this item </h1>
{% endif %}

详情: item 是上下文项。和item.bargain.first 让您获得第一件便宜货。

在您的app/urls.py 你可以这样写你的网址:

urlpatterns = [
   ....
   path('product/<int:pk>', ItemDetailView.as_view()),
]

【讨论】:

  • 感谢您的回答,但 /product/6/ 'pk' 处出现错误 KeyError
  • @AmaeraaSethi 我更新了答案,请检查(特别是 urls.py)。
猜你喜欢
  • 2013-09-29
  • 1970-01-01
  • 2012-06-18
  • 2021-03-21
  • 1970-01-01
  • 2021-04-02
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多