user985541
user985541

Reputation: 727

Django many to many filtering optimization

Do you have any idea how to opitimize (time) this query? It is so slow even if wordpress population is around 1000.

query:

al = Wordpress.objects.all().order_by('?')
zaplecza = Wordpress.objects.none()
for l in labels.split(","):
    zaplecza = zaplecza | al.filter(label = l)    
zaplecza = zaplecza.exclude(wordpress__url = project_name) <--very slow

models.py

class Wordpress(models.Model):
    url = models.CharField(max_length = 1000)
    login = models.CharField(max_length = 1000, default = "admin")
    password = models.CharField(max_length = 1000, default = "perkoz")
    label = models.CharField(max_length = 1000)
    cms = models.CharField(max_length = 1000)


class Project(models.Model):
    url = models.CharField(max_length = 1000)
    links = models.TextField(blank = True, null = True, verbose_name = "Linki do wpisów")
    wordpress = models.ManyToManyField(Wordpress, related_name = "wordpress", verbose_name = "Dodane do zaplecz")

    main_link = models.CharField(max_length = 1000)
    dir_links = models.TextField(blank = True, null = True, verbose_name="Anchory")
    blog_links = models.TextField(blank = True, null = True, verbose_name="Lista linków i anchorów z ;;;")
    category = models.ForeignKey(Category, related_name = "projekt")
    kategorie = models.CharField(max_length = 1000)
    labels = models.CharField(max_length = 1000)
    tagi = models.CharField(max_length = 1000)
    auto_tekst = models.BooleanField(verbose_name="Auto tekst")
    arts = models.TextField(blank = True, null = True, verbose_name="Artykuły")
    title = models.TextField(blank = True, null = True, verbose_name="Tytuł")
    no = models.IntegerField(blank = True, null = True, verbose_name="Liczba wpisów")
    last_added = models.DateTimeField(blank = True, null = True, verbose_name="Ostatnio dodane")

Upvotes: 1

Views: 3005

Answers (1)

mariodev
mariodev

Reputation: 15594

You're fetching m2m related objects, so you should use prefetch_related in your query to optimize it.

https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.prefetch_related

Upvotes: 1

Related Questions