I have a Django model User
class Notification(TimeStampedModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'),
related_name='notifications')
viewed = models.BooleanField(verbose_name=_('has viewed'), default=False)
def make_viewed(self):
if self.viewed:
return
self.viewed = True
User.objects.filter(id=self.user.id).update(not_viewed_notifications=F('not_viewed_notifications') - Value(1))
self.save()
So I think that order methods in model is bad idea and actually
it's anti-pattern, so next one solution was like this:
class Notification(TimeStampedModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'),
related_name='notifications')
_viewed = models.BooleanField(verbose_name=_('has viewed'), default=False)
@property
def viewed(self):
return self._viewed
@viewed.setter
def viewed(self, value):
if self._viewed:
return
self._viewed = True
self.user.not_viewed_notifications = F('not_viewed_notifications') - Value(1)
self.user.save(commit=False)
self.save()
It looks better, but we have a couple of problems:
1) Model have methods yet
2) Property care side-effect, it doesn't obviously
3) That action require access to instance, so we can't move it to custom field.
What are you thinking about?
notification.viewed = False
and it will setnotification._viewed
toTrue
and remove anot_viewed_notifications
from the user? \$\endgroup\$