我有以下 Django 模型:
class User(models.Model):
username = models.CharField(max_length=50, unique=True)
name = models.CharField(max_length=100)
class Url(models.Model):
user = models.ManyToManyField(User)
url = models.URLField()
class Keywords(models.Model):
url = models.ManyToManyField(Url)
keyword = models.CharField(max_length=100)
现在,我想要数据库中任意两个用户的所有常用关键字:
username1 = 'user1'
username2 = 'user2'
尝试1:
Keyword.objects.filter(url__user__username=username1).filter(url__user__username=username2).values('keyword', 'url__url').distinct()
// Returns empty list [] [ Wrong ]
尝试2:
k1 = [ k.keyword for k in Keyword.objects.filter(url__user__username=username1) ]
k2 = [ k.keyword for k in Keyword.objects.filter(url__user__username=username2) ]
common_k = list(set(k1).intersection(set(k2)))
print common_k
// Return list of common keys (As Expected) [ Correct ]
我在尝试 1 中做错了什么?
请注意:乍一看.filter(url__user__username=username1).filter(url__user__username=username2)
似乎是错误的,但它有一个多对多的关系,它应该可以工作。
尝试 1 的测试输入
newuser1 = User.objects.get(username='newuser1')
newuser2 = User.objects.get(username='newuser2')
url = Url(url='http://common.com/')
url.save()
url.user.add(newuser1)
url.user.add(newuser2)
key = Keyword(keyword='common')
key.save()
key.url.add(url)
现在,我对此进行了尝试 1 和尝试 2,并得到了预期的正确结果。我得到andcommon
的关键字。newuser1
newuser2
现在,尝试 2 肯定是正确的,那么我在尝试 1 中做错了什么?