lundi 8 août 2016

Patterns for creating and updating related models in django

Assuming i have two models:

class PhotoAlbum(models.Model):
    name = models.CharField(max_length=255)

class Photo(models.Model):
    album = models.ForeignKey(to=PhotoAlbum)
    photo = models.ImageField(upload_to=".")

I wish to give user a form, on which he could provide the "name" of album, and i have some logic how to create album with photos from the given name. I assumed that i need to create some additional service here:

class PhotoAlbumService:
    def __init__(self, album):
        self._album = album
        self._photos = list(self._album.photo_set.all())

    def create(self):
        # creation logic here
        # some common function for creation and updating

    def update(self):
        # updating logic here
        # again the common function for creation and updating
        # additional unique logic for updating

    def _update_only_method(self):
        # will be called only on update

    def _common_logic(self):
        # common logic both for create and update

and in my views.py im doing something like this for creation:

AlbumService(Album(name="user_provided_name")).create()

and for updating:

AlbumService(Album.objects.get(pk=1)).update()

But i confused, because, for example, for creation - i dont need to have a list of photos (there is no photo before creation) and method, which is used only for update is not needed for creation. Also - on each creation or updating - the new instance of service is created. I'm definitely not satisfied with this behavior. Maybe there is some useful patterns which normalize such behavior?

Aucun commentaire:

Enregistrer un commentaire