Answer the question
In order to leave comments, you need to log in
How to implement fetch from mysql tables related as one to many?
There are signs in the database:
BlogRecord - the number of entries is more than 30,000.
Comment - the number of entries is more than 250,000.
Everything is implemented on Django, the models look something like this:
class BlogRecord(models.Model):
text = models.TextField(null=True, blank=True)
# прочие поля
class Comment(models.Model):
blog_record = models.ForeignKey(BlogRecord, db_index=True)
# прочие поля
# сложная выборка по разным полям из таблицы комментариев
comments = models.Comment.objects.filter()
blog_record = models.BlogRecord.objects.filter(
id__in=comments.values_list('blog_record')
)
comment_ids = # Большой список ID комментариев полученный в результате выборки.
models.BlogRecord.objects.filter(id__in=comment_ids)
Answer the question
In order to leave comments, you need to log in
It is possible to try to transfer conditions of selection of comments to the second request.
For example, like this:
blog_record = models.BlogRecord.objects.filter(comment__author=103, comment__status='publish')
I didn’t quite understand what you want to do, but it definitely needs to be done in one request.
"By transferring some of the calculations to Python code" you only slow down the process. The fastest selection is made on the side of the DBMS - it is written in C and optimized as much as possible. Therefore, whatever you do there, try to put it in one request.
Describe what result you want to get, then it will be easier to suggest.
Did as suggested by @yamel :
comment_params = {"comment__author":103}
blog_records = models.BlogRecord.objects.filter(
**comment_params
).annotate(Count('comment__blogrecord'))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question