python - Override save method force me to save twice in the admin thing -
working on django1.8.4
so, got models :
class occurences(models.model): datetime = models.datetimefield() class serie(models.model): first_occurence = models.datetimefield(null=true, blank=true) last_occurence = models.datetimefield(null=true, blank=true) occurences = models.manytomanyfield(occurence, null=true, blank=true) def save(self, *args, **kwargs): super(series, self).save(*args, **kwargs) self.first_occurence = self.occurences.order_by['-datetime'].first() self.last_occurence = self.occurences.order_by['datetime'].last() super(series, self).save(*args, **kwargs)
working great on manage.py shell.
but use admin interface make modifications, doesn't work directly. have modify occurences field, save it, , reload resave once again @ end...
i've tried super(...).save(...) @ beginning of save function, @ beginning , @ end of (twice), @ end.
my goal able order first_occurence (or last, 1 enough).
serie.objects.order_by('first_occurence__datetime')
because doesn't work
serie.objects.order_by('occurence__first') serie.objects.order_by('occurence__first__datetime') serie.objects.order_by('occurence__set__first')
i don't :/
these explicit references first_occurence
, last_occurence
unnecessary, django orm. of functionality provide available implicitly through manytomany field occurences
.
if add meta.ordering
attribute occurences
model, can query first , last. example:
class occurence(models.model): datetime = models.datetimefield() class meta: ordering = ('datetime',) class series(models.model): first_occurence = models.datetimefield(null=true, blank=true) last_occurence = models.datetimefield(null=true, blank=true) occurences = models.manytomanyfield(occurence, null=true, blank=true) my_series = series.objects.get(...) first = my_series.objects.earliest() latest = my_series.objects.latest()
also, given above, able sort occurences see have latest (or earliest) occurences. example:
series_with_latest_occurences = series.objects.order_by('-occurences__datetime') series_with_earliest_occurences = series.objects.order_by('occurences__datetime')
Comments
Post a Comment