【问题标题】:Django INNER JOIN using foreign key with WHERE clauseDjango INNER JOIN 使用带有 WHERE 子句的外键
【发布时间】:2014-07-17 04:28:32
【问题描述】:

所以我有一个用户正在关注其他用户的数据库结构。在内置的用户模型中,我有“first_name”、“username”等字段……友谊模型如下:

class Friendship(models.Model):
    tail_user = models.ForeignKey(User,related_name='follower')   #The one who sent the friend request
    head_user = models.ForeignKey(User,related_name='followed')

某些用户在给定时刻没有名字,稍后会更新。现在对于一个特定的用户(比如演员),我想得到他所有有名字的朋友。像这样的

SELECT * FROM friendship JOIN user ON friendship.head_user_id=user.id WHERE user.first_name != ''

如果可能不使用子查询,我如何在 Django ORM 中实现这一点。

我提供的sql查询可能是错误的,只是为了传达我想要表达的意思

【问题讨论】:

    标签: python mysql sql django


    【解决方案1】:

    您可以exclude() 空的 first_name 值:

    Friendship.objects.exclude(head_user__first_name='')
    

    请注意,如果first_nameNULL(不是空字符串),则需要使用__isnull

    Friendship.objects.exclude(head_user__first_name__isnull=True)
    

    而且,是的,如果您确实想排除 NULL 和空值,您可以链接排除:

    Friendship.objects.exclude(head_user__first_name__isnull=True) \
                      .exclude(head_user__first_name='')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-02
      • 2013-08-11
      • 2010-11-04
      • 1970-01-01
      • 2012-04-25
      • 2015-08-21
      • 1970-01-01
      • 2021-06-18
      相关资源
      最近更新 更多