moviewyrm/bookwyrm/models/base_model.py

45 lines
1.5 KiB
Python
Raw Normal View History

2020-03-07 06:56:44 +00:00
''' base model with default fields '''
from django.db import models
from django.dispatch import receiver
from bookwyrm.settings import DOMAIN
from .fields import RemoteIdField
2020-09-21 15:16:34 +00:00
class BookWyrmModel(models.Model):
''' shared fields '''
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
2020-11-30 18:32:13 +00:00
remote_id = RemoteIdField(null=True, activitypub_field='id')
def get_remote_id(self):
''' generate a url that resolves to the local object '''
base_path = 'https://%s' % DOMAIN
if hasattr(self, 'user'):
base_path = self.user.remote_id
2020-02-18 01:53:40 +00:00
model_name = type(self).__name__.lower()
return '%s/%s/%d' % (base_path, model_name, self.id)
class Meta:
''' this is just here to provide default fields for other models '''
abstract = True
2020-12-31 01:36:35 +00:00
@property
def local_path(self):
''' how to link to this object in the local app '''
return self.get_remote_id().replace('https://%s' % DOMAIN, '')
2020-05-14 01:23:54 +00:00
@receiver(models.signals.post_save)
2020-12-13 02:06:48 +00:00
#pylint: disable=unused-argument
def execute_after_save(sender, instance, created, *args, **kwargs):
''' set the remote_id after save (when the id is available) '''
2020-05-14 01:23:54 +00:00
if not created or not hasattr(instance, 'get_remote_id'):
return
2020-05-14 18:28:45 +00:00
if not instance.remote_id:
instance.remote_id = instance.get_remote_id()
2021-02-07 00:13:59 +00:00
try:
instance.save(broadcast=False)
except TypeError:
instance.save()