我是Django的新手,我正在尝试从表UserBookmark
中获取记录,其中tag等于category。
我的代码如下:
views.py:
def home(request):
category=Category.objects.values_list('category',flat = True).filter(user=request.user.pk)
category = list(category)
print category
bookmarks = UserBookmark.objects.filter(tag__name__in = category)
print bookmarks
return render(request,'home.html',{'bookmarks':bookmarks})
models.py:
class Category(models.Model):
user = models.ForeignKey(User)
category= models.CharField(max_length=100)
def __str__(self):
return '%s %s'%(self.user,self.category)
class UserBookmark(models.Model):
user = models.ForeignKey(User)
bookmark = models.URLField()
tag = TaggableManager()
def __str__(self):
return '%i %s %s'%(self.id,self.user,self.bookmark)
但是当我在views.py
中打印书签时,我得到一个空集。我也尝试打印类别,它给出了:
u"[u'Data Science', u'Python', u'Android', u'Data Analytics']"]
当我在shell中尝试这个时:
UserBookmark.objects.filter(tag__name__in = [u'Data Science', u'Python', u'Android', u'Data Analytics'])
我得到了一个结果集
<QuerySet [<UserBookmark: 24 user12 https://github.com/shreyag12?tab=stars>, <UserBookmark: 24 user12 https://github.com/swapnil?tab=stars>, <UserBookmark: 26 user13 https://github.com/retme7/My-Slides>, <UserBookmark: 26 user13 https://github.com/retme7/My-Slides>, <UserBookmark: 26 user13 https://github.com/retme7/My-Slides>, <UserBookmark: 27 user14 https://github.com/sunny2krGupta/Bigquery-series>, <UserBookmark: 28 user14 https://github.com/ctfs/write-ups-2017>]>
有人可以指导我吗?
答案 0 :(得分:0)
我通过转换看起来像这样的类别来解决这个问题
u"[u'Data Science', u'Python', u'Android', u'Data Analytics']"]
类别2 = ast.literal_eval(类别[0])
类别2 [u&#39;数据科学&#39;,你&#39; Python&#39;,你&#39; Android&#39;,u&#39;数据分析&#39;]和
然后使用bookmarks = UserBookmark.objects.filter(tag__name__in = category2)
有效!