Django 反向查找查询在三个表中



我有三个表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'})

提前非常感谢!

在您的

评论后更新:

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)

相关内容

  • 没有找到相关文章

最新更新