[Answered ]-Better many to many filtering logic

1πŸ‘

βœ…

This works, however, I feel like there is better and faster filtering I don’t know of yet. Is there?

This is implemented efficiently. A database will construct indices for columns that have a ForeignKey, to retrieve related objects in an efficient way. When you filter with:

ModelB.objects.filter(liked=user).order_by('-date')

then this will run a query with:

SELECT appname_modelb.*
FROM appname_modelb
INNER JOIN appname_modelb_liked.model_b_id = appname_modelb
WHERE appname_modelb_liked.user_id = id_of_user
ORDER BY appname_modelb.date DESC

You can probably slightly boost efficiency by adding an index on the date field to do the ordering step more efficient:

class ModelB(models.Model):
    user = models.ForignKey(ModelA, ondelete=models.CASCADE)
    liked = models.ManyToManyField(ModelA, blank=True)
    date  = models.DateTimeField(auto_now_add=True, db_index=True)

Leave a comment