0

I have three tables User, Users_clients, and Credits. I want to list tables of current user's clients with their details and credit. If any client is listed in credit table then credit should return 0 where else it should return the credit value.

my model.py is

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)

my views.py is

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'})

Thanks a lot in advance!

  • You should not use `User_clients`, but you should add a field within user: `clients = models.ManyToManyField('User')`, then, you could do `data = User.objects.get(id=request.user.id).clients.all()` – Blusky Oct 12 '17 at 21:05

1 Answers1

1

updating after your comment:

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)
  • Thanks a lot Mr. Efkin but this query returns client who has credits in credit table. Here I want to fetch all the client whether client has credits or not. Let's say. if credit table credits table is empty then it should returns 0. – xyzwithashok Oct 12 '17 at 21:17
  • sorry i misunderstood your question, i'm updating an answer –  Oct 12 '17 at 21:25
  • Many many thanks Mr. Efkin, Is it possible to make a query that fetch all clints in my tree. here we are fetching clients that are created by me only. For example here I'm a reseller and I make clients which can be resellers and end clients also. So now I want fetch all clients that are in my tree. – xyzwithashok Oct 16 '17 at 13:17