0

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

提前非常感谢!

4

1 回答 1

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)
于 2017-10-12T21:08:31.130 回答