简体   繁体   中英

Django Query Count Records on Row

I'm a little rusty with django.

I'm wondering if anyone can tell me how I count the db objects from this query:

UserEnteredTld = Tld.objects.filter(FKtoClient=request.user, auth=0)

I used to do:

UserEnteredTld = Tld.objects.filter(FKtoClient=request.user, auth=0).count()

In the template (with the var):

{% if UserEnteredTld  %}    
    <h3>I have Tld's</h3>
{% endif %}

the view:

UserEnteredTld = Tld.objects.filter(FKtoClient=request.user, auth=0).count()
UserAuthTld = Tld.objects.filter(FKtoClient=request.user,auth=1).count()

return render(request, 'accounthome.html', {
         'UserEnteredTld':UserEnteredTld,
         'UserAuthTld':UserAuthTld
    })

model

class Tld(models.Model):
    auth = models.BooleanField(default=False)
    FKtoClient = models.ForeignKey(User) 

but, this appears to not be outputting anything. (I verified actual rows exist...)

To be clear: I'm simply trying to count the number of rows for the Tld table where a ForeignKey exists for the logged in user and the auth=0 .

Don't use count for that. Use exists ( docs ).

user_entered_tld = Tld.objects.filter(FKtoClient=request.user, auth=False).exists()

{% if user_entered_tld  %}    
    <h3>I have Tld's</h3>
{% endif %}

Some notes:

  • Django latest version is 1.7 (on beta). It's impossible you're using 2.6.2 (that seems like a Python version)
  • Don't camel-case your variables. Use user_entered_tld instead of UserEnteredTld . It's a good Python convention.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM