【发布时间】: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