Anoop K George
Anoop K George

Reputation: 1735

Django, queryset to find count in manytomany field

I have below model,

class Blog(models.Model):
    name = models.CharField(max_length=100)

class Author(models.Model):
    name = models.CharField(max_length=200)

class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    head = models.CharField(max_length=255)
    authors = models.ManyToManyField(Author)

How do I find authors count ?

Let us say I have an Entry object as Entryobject (Entryobject = Entry.objects.filter(blog__name='a') ), I tried as below but got attribute error.

Entryobject.authors.count() # got error here

Also please let me know how can I query list of authors in Entryobject .

Upvotes: 1

Views: 280

Answers (1)

JSRB
JSRB

Reputation: 2613

You can query a list of authors like so:

Entryobject = Author.objects.all() or
Entryobject = Author.objects.values_list('name', flat=True)

Regarding flat=True I'd like to reference the official docu. Basically it returns a Queryset with single values rather than tuples, example:

>>> Entry.objects.values_list('id').order_by('id')
<QuerySet[(1,), (2,), (3,), ...]>

>>> Entry.objects.values_list('id', flat=True).order_by('id')
<QuerySet [1, 2, 3, ...]>

Also regarding your error, I think it should be an uppercase B:

Entryobject = Entry.objects.filter(Blog__name='a')

Upvotes: 2

Related Questions