H
H
huko2017-02-16 17:10:19
Django
huko, 2017-02-16 17:10:19

How to optimize the model?

There is a model like this:

class Ip(models.Model):
    ip = models.GenericIPAddressField(protocol="IPv4", verbose_name="IP")
    is_active = models.BooleanField(default=True)

class User(models.Model):
    name = models.CharField(_('Name of User'), max_length=255)
    ips = models.ManyToManyField(Ip, blank=True, related_name="user_ip")
    def get_ip_count(self):
        return "{}/{}".format(self.ips.filter(is_active=True).count(),
                      self.ips.filter(is_active=False).count())

How can get_ip_count be optimized so that it doesn't spawn a bunch of subrequests? Probably somehow through select_related but I can't figure out how.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question