【问题标题】:Accessing fields in a Queryset from a ManytoManyFIeld从 ManytoManyFIeld 访问查询集中的字段
【发布时间】:2020-10-01 13:04:16
【问题描述】:

对 Django 和模型来说还很陌生,我正在尝试制作一个愿望清单,人们可以在其中添加到愿望清单中,然后通过单击愿望清单的链接查看他们的愿望清单中的内容。我为愿望清单创建了一个单独的模型,该模型具有用户的外部字段,然后是他们想要添加到愿望清单中的项目的多对多字段。现在我正在尝试使用 Django 中的管理视图查看我为用户创建的愿望清单。

我遇到的问题是,当我尝试将他们的愿望清单打印到模板时,页面上会出现以下内容。

<QuerySet [<listings: item: Nimbus, description:this is the nimbus something at a price of 300 and url optional(https://www.google.com/ with a category of )>, <listings: item: broom, description:this is a broom stick at a price of 223 and url optional(www.youtube.com with a category of broom)>, <listings: item: wand, description:this is a wand at a price of 3020 and url optional(www.twitter.com with a category of sales)>]>

理想情况下,我想要的是拆分查询集,这样当我遍历基于用户的项目时,两个列表及其信息将位于 html 页面上的单独行上。我知道它必须来自我在模型本身上设置的字符串表示,但不知道如何实现这一点。我尝试了 .all、.values、.values_list、.prefetch_related,当我转到页面和或不可迭代时,我仍然得到相同的结果

如果有什么好处的话,那就是可以访问商品、描述和价格,并将其打印到愿望清单中每件商品的页面上。

这是否可行,或者我的方法是否错误,是否应将愿望清单添加到其他形式之一,但我认为这应该以某种方式起作用。不知道我是否已经接近,或者我的某个文件中缺少某些内容,或者需要创建一个新的单独视图。

代码如下:

models.py

class User(AbstractUser):
    pass

class listings(models.Model):
    item = models.CharField(max_length=100)
    description = models.CharField(max_length=100)
    price = models.IntegerField()
    url = models.CharField(max_length=100,blank=True)
    category = models.CharField(max_length=100,blank=True)

    def __str__(self):
        return f"item: {self.item}, description:{self.description} at a price of {self.price} and url optional({self.url} with a category of {self.category})"
        

class bids(models.Model):
    desired = models.ForeignKey(listings,on_delete=models.CASCADE,related_name="desired",null=True)
    bid = models.IntegerField()

    def __str__(self):
        return f"{self.desired} Bid: {self.bid}"


class comments(models.Model):
    
    information = models.ForeignKey(listings,on_delete=models.CASCADE, related_name ="Review",null=True)
    title = models.CharField(max_length=100)
    comment = models.CharField(max_length=100)

    def __str__(self):
        return f"title {self.title} Comment: {self.comment}"

class wl(models.Model):
    user = models.ForeignKey(User ,on_delete=models.CASCADE, related_name="users")
    product = models.ManyToManyField(listings, related_name="item_wished")

    def __str__(self):
        return f"{self.product.all()}"

views.py


def watch_list(request):


    user = wl.objects.filter(user_id = request.user.id).prefetch_related('product')
    
    return render(request, 'auctions/wishlist.html',{
        'wishes': user
    })


html模板

{% extends "auctions/layout.html" %}

{% block body %}
    <h2>Active Listings</h2>
    {% for i in wishes.all %}

    
        <li> {{ i }} <li>

    {% endfor %}
{% endblock %}


【问题讨论】:

    标签: python django django-models django-templates manytomanyfield


    【解决方案1】:

    您的代码看起来不错。试着用结构调整你的模板,也许是一个 HTML 表格:

    {% extends "auctions/layout.html" %}
    
    {% block body %}
        <h2>Active Listings</h2>
    
        <table>
        {% for w in wishes %}
            <tr>
                <td>{{ w.pk }}</td>
                <td>{{ w.product.item }}</td>
                <td>{{ w.product.description }}</td>
                <td>{{ w.product.price }}</td>
            </tr>
        {% endfor %}
        </table>
    {% endblock %}
    

    【讨论】:

    • 当我只在 pk 字段中添加其他字段时,这不起作用,但是当我尝试执行 w.product.item 等其他字段时,它变为空白,然后什么也没有显示。你认为我只需要以某种方式重新排列我的代码。 .
    【解决方案2】:

    查询将返回所有 wl 对象。与:

    {% for w in wishes %}
    

    您遍历所有 wl 对象。每个“w”都有“product”字段,这是一个多对多关系——它包含多个对象,需要再次迭代:

    {% for each_wl in wishes %}
         {% for each_product in each_wl %}
               {{ each_product.item }}
    

    另外,将变量/类命名为更详细的名称。

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      相关资源
      最近更新 更多