How to look at two models at the same time

0

I have the following models:

class Videos(models.Model):
    title = models.CharField(max_length=45)

class TimelinePoints(models.Model):
    description = models.CharField(max_length=45)
    videos_id = models.ForeignKey('Videos', models.DO_NOTHING, db_column='Videos_id')
    # ... Otros campos sin importancia

I want to do a search by bringing all the videos whose title contains the string entered by the user, and all the videos whose TimelinePoint also contain that string in their description field.

Until now I was solving it in the following way:

videos = Videos.objects.filter(Q(title__icontains = string_ingresado) | Q(timelinepoints__description__icontains = string_ingresado))

But later I realized that my application needs to have the list of descriptions of TimelinePoints matched, so I had to add this query below:

timeline_points = TimelinePoints.objects.filter(description__icontains = string_ingresado).only('description')

This does not convince me much since I am doing an expensive process 2 times. So my question is:

Is there a way to do what I need without having to do the same search twice?

    
asked by Genarito 26.03.2017 в 22:55
source

1 answer

1

Perhaps what I find least cost to solve the problem is to make this queryset:

TimelinePoints.objects.filter(
    Q(descripcion__icontains=string) | Q(videos_id__title__icontains=string)
).select_related('videos_id')

Bearing in mind that this way you are doing a single query to the database, in the timeline table, you are looking for the timeline that in your description has the string, and the timeline that the videos have in the title the string, then you are doing a select_related to the table of videos to bring them in the same query, the only thing is that some fields can be repeated, so it is important to spend a distinct() I hope I have helped you.

    
answered by 27.03.2017 / 22:36
source