在我的Django应用程序中,我有两种模型,一种是“用户”,另一种是“友谊”。两者之间存在“多对多”关系,因为“用户”可以有许多“朋友”,而“朋友”可以有许多其他“用户”朋友。
如何返回所有与first_name ='Daniel'不是用户的朋友(名字和姓氏)?
Models.py:
class Friendships(models.Model):
user = models.ForeignKey('Users', models.DO_NOTHING, related_name="usersfriend")
friend = models.ForeignKey('Users', models.DO_NOTHING, related_name ="friendsfriend")
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'friendships'
class Users(models.Model):
first_name = models.CharField(max_length=45, blank=True, null=True)
last_name = models.CharField(max_length=45, blank=True, null=True)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'users'
到目前为止,这是我在控制器中尝试过的方法(views.py)-请注意,我知道控制器应该很薄,但仍然要道歉。我在下面的代码段中尝试过(在多次尝试使用更清洁的方法失败之后)是尝试并首先抓住丹尼尔斯的朋友(将它们填充到列表中,然后删除所有重复的ID),然后按其ID过滤掉它们。
# show first and last name of all friends who daniel is not friends with:
def index(req):
friends_of_daniel = Friendships.objects.filter(user__first_name='Daniel')
daniels_friends = []
for friend_of_daniel in friends_of_daniel:
daniels_friends.append(friend_of_daniel.friend.id)
daniels_friends = list(set(daniels_friends))
not_daniels_friends = Friendships.objects.exclude(id__in=daniels_friends)
context = {
'not_daniels_friends':not_daniels_friends,
}
return render(req, "friendapp/index.html",context)
但是,当我在视图(模板)文件中尝试以下操作时,仍然看到作为Daniels朋友的个人。知道我在做什么错吗?
<ul>
{% for not_daniel_friend in not_daniels_friends %}
<li>{{ not_daniel_friend.user.first_name }} {{ not_daniel_friend.user.last_name }}</li>
{% endfor %}
</ul>
尝试此操作,在friend_of_daniel.friend.id的位置,您应该从用户模型中排除结果。
像这样的东西:
def index(req):
friends_of_daniel = Friendships.objects.filter(user__first_name='Daniel')
daniels_friends = []
for friend_of_daniel in friends_of_daniel:
daniels_friends.append(friend_of_daniel.friend.id)
daniels_friends = list(set(daniels_friends))
not_daniels_friends = Users.objects.exclude(id__in=daniels_friends)
context = {
'not_daniels_friends':not_daniels_friends,
}
return render(req, "friendapp/index.html",context)
谢谢。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句