I need an easy control of what products shown on which site, and since there are lots of products, I would also like to set product sites via category, producer and tags. So I show a product on a site if the product OR (its category AND its producer AND one of its tags) are linked to the site. The code I ended up with is the following (simplified):
from django.db.models import Model, ManyToManyField, ForeignKey, BooleanField
class Site(Model):
enabled = BooleanField()
class Producer(Model):
sites = ManyToManyField(Site)
class Category(Model):
sites = ManyToManyField(Site)
class Tag(Model):
sites = ManyToManyField(Site)
class Product(Model):
producer = ForeignKey(Producer)
category = ForeignKey(Category)
tags = ManyToManyField(Tag)
sites = ManyToManyField(Site)
def get_site_ids(self):
if self.sites.exists():
return list(self.sites.values_list('id', flat=True))
else:
p = list(self.producer.sites.values_list('id', flat=True))
c = list(self.category.sites.values_list('id', flat=True))
t = sum([list(tag.sites.values_list('id', flat=True)) for tag in self.tags.all()], [])
ids = set.intersection(set(p), set(c), set(t))
return ids
My question is how can I optimize get_sites method? Is it possible to join some of the queries?
Update: I am interested just in site ids which will be indexed and stored by search engine.