These are the models i have in my small project
class Tag(models.Model):
name = models.CharField(max_length=200)
class Post(models.Model):
content = models.CharField(max_length=200)
tags = models.ManyToManyField(Tag)
location = models.PointField(null=True, blank=True)
A list of tags are given to me (a maximum of 3). I need to find the number of times tag each of these tags appear on Post. lets say ["funny","geek","tech"]
For getting tag count i am doing
for tag in tags:
tag_data[tag] = Post.objects.filter(
tags__name=tag,
location__distance_lte=(
pnt, D(km=distance))).count()
Then i fetch all post data using the following query.
posts = Post.objects.filter(
tags__name__in=tags,
location__distance_lte=(pnt, D(km=distance)))
I am already looping on posts at the end of function.
for post in posts:
#some logic
So i know i have the tags data there. No need to do seperate data queries like above to find count. But i figured out that if i want to find count of tags inside the for loop i need 1 more for loop inside that for loop.
for post in posts:
#some logic
for tag in post.tags:
#some logic
So my question which one is more efficient in here. Fetching using .count() as i did or nested for loops.