【问题标题】:Get django model correctly正确获取 django 模型
【发布时间】:2020-12-17 18:11:51
【问题描述】:

我正在尝试获取模型的值并使用 for 循环获取值,但它给了我这个


我希望它打印

Gazou
Gazou
Gazou
Gazou
Gazou
Gazou

[<Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>, <Watchlist: Gazou>]

我的意见.py


def watchlist(request):
if request.method=='POST':
    name = User.objects.get(username=request.user.username)
    title = request.POST['title']
    print(name)
    listing = Listing.objects.get(title=title)
    all_titles = Watchlist.objects.filter(name=name)
    print(all_titles)
    print(title)
    msg = "You already have this on your watchlist"
    a = []
    for item in all_titles: 
        a.append(item)
    print(a)
    if title in a:
        return HttpResponseRedirect(reverse("index"))
    else:
        watchlist = Watchlist.objects.create(taitle=title, name=name, title=listing)
        return HttpResponseRedirect(reverse("index"))
    
    
else:
    user = request.user
    watchlist = Watchlist.objects.filter(name=user)
    return render(request, "auctions/watchlist.html", {
            "watchlist": watchlist
    })

我的模型.py

class Watchlist(models.Model):
name = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
taitle = models.CharField(max_length=100, null=True)
title = models.ForeignKey(Listing, on_delete=models.CASCADE, null=True)
def __str__(self):
    return f"{self.taitle}"

我正在使用 django 1.11.29 和 python 3.8.5

【问题讨论】:

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


    【解决方案1】:
    for item in all_titles: 
        a.append(item.name)   #Append only name.
    print(a)
    

    【讨论】:

      猜你喜欢
      • 2016-10-01
      • 2021-06-07
      • 2022-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      • 2022-07-11
      相关资源
      最近更新 更多