Note that there are some explanatory texts on larger screens.

plurals
  1. POIssue with models/manager to organize a query
    primarykey
    data
    text
    <p>I have an application to count the number of access to an object for each website in a same database.</p> <pre><code>class SimpleHit(models.Model): """ Hit is the hit counter of a given object """ content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') site = models.ForeignKey(Site) hits_total = models.PositiveIntegerField(default=0, blank=True) [...] class SimpleHitManager(models.Manager): def get_query_set(self): print self.model._meta.fields qset = super(SimpleHitManager, self).get_query_set() qset = qset.filter(hits__site=settings.SITE_ID) return qset class SimpleHitBase(models.Model): hits = generic.GenericRelation(SimpleHit) objects = SimpleHitManager() _hits = None def _db_get_hits(self, only=None): if self._hits == None: try: self._hits = self.hits.get(site=settings.SITE_ID) except SimpleHit.DoesNotExist: self._hits = SimpleHit() return self._hits @property def hits_total(self): return self._db_get_hits().hits_total [...] class Meta: abstract = True </code></pre> <p>And I have a model like:</p> <pre><code>class Model(SimpleHitBase): name = models.CharField(max_length=255) url = models.CharField(max_length=255) rss = models.CharField(max_length=255) creation = AutoNowAddDateTimeField() update = AutoNowDateTimeField() </code></pre> <p>So, my problem is this one: when I call <code>Model.objects.all()</code>, I would like to have one request for the SQL (not two). In this case: one for Model in order to have information and one for the hits in order to have the counter (hits_total). This is because I cannot call directly <code>hits.hits_total</code> (due to SITE_ID?). I have tried <code>select_related</code>, but it seems to do not work...</p> <p>Question: - How can I add column automatically like <code>(SELECT hits.hits_total, model.* FROM [...])</code> to the queryset? - Or use a functional <code>select_related</code> with my models?</p> <p>I want this model could be plugable on all other existing model.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload