python - Django: Default ordering based on a many-to-many related field values and counts -
models following:
class weekday(models.model): ''' >>> w in weekday.objects.all(): ... print w ... sunday monday tuesday wednesday thursday friday saturday ''' name = models.charfield(max_length=9) def __unicode__(self): return self.name class stop(models.model): class meta: ordering = ???? name = models.charfield('stop name', max_length=32) days_open = models.manytomanyfield(weekday)
the kind of ordering want is:
- everything has 7 days
- everything has sunday
- everything has monday
- etc, etc. (with tie breaker being count of weekdays , stop's name)
anyone have suggestions on how approach this? should done in manager somehow? or perhaps there's simple way this?
appreciate it!
you can specify model fields in meta.ordering, if want implement logic described, have resort custom manager.
edit:
you add kind of weight
field stop
model, update field along updating days_open
, able use ordering = ['-weight']
alternatively, might fit purposes:
stop.objects.annotate(weight=models.sum('weekday__weight')).order_by('-weight')
-- of course require adding weight
field weekday
model , pre-filling records. implemented method in custom manager mentioned above.
Comments
Post a Comment