Reputation:
I would like to represent my data in a form of a chart, but i am having a problem making the right queries to display the chart's labels and series , and basically i have a Book model , and a User model and i want to display the number of books(series) that belongs to a particular user(labels) .
class Book(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=200)
@register.simple_tag()
def chart_data():
users =
books =
return json.dumps({
'labels':[user.username for user in users],
'series':[[book.name for book in books]]
})
Upvotes: 0
Views: 61
Reputation: 3051
If I understand correctly, You need a json data which should have a label represents username and series representing book.name for that particular user.
Have you tried :
books = Book.objects.values('user__username', 'name').order_by('user__username', 'name')
Upvotes: 0
Reputation: 1632
If you want to do it for a particular user, then:
series = Books.objects.filter(user = "username").values("name")
This will produce a queryset:
<queryset: [{name: book1}, {name: book2}, ...]>
You can convert it to list like so:
list(series)
and then send it through json.dumps..
In the above case, you already know the user those books belongs too, but if you want specify it through the query, then:
series = Books.objects.filter(user = "username").values("name", "user__username")
This will produce something like this:
<queryset: [{name: book1, user: username1}, {name: book2, user: username1}, ...]>
Upvotes: 0
Reputation: 2693
Something like this:
users = User.objects.all()
for user in users:
books = Book.objects.filter(user=user)
Upvotes: 1