django反向查询三个表内的查询

时间:2017-10-12 20:51:58

标签: python django django-models django-queryset reverse-lookup

我有三个表User,Users_clients和Credits。 我想列出当前用户客户的表格及其详细信息。 如果任何客户在信用表中列出,那么信用应该返回0,否则它应该返回信用值。

我的model.py是

class User_clients(models.Model):
user = models.ForeignKey(User, related_name='myuser')
client = models.ForeignKey(User, related_name='myclient')

class Credits(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
credit = models.IntegerField(null=True, default=0)

我的views.py是

def clients(request):
try:
    data = User_clients.objects.order_by('-id').filter(user_id=request.user.id)[0:10]
except User_clients.DoesNotExist:
    data = None
return render(request, "client_list.html",{'title':"Client List",'clients':data,'active':'myclients','open':'clients'})

提前多多感谢!

1 个答案:

答案 0 :(得分:1)

评论后更新:

from itertools import chain
from django.db.models import F


without_credit = User_clients.objects.filter(user=request.user, client__credits__is_null=True).annotate(credit=0)
with_credit = User_clients.objects.filter(user=request.user, 
client__credits__is_null=False).annotate(credit=F("client__credits__credit"))
data = chain(without_credit, with_credit)