python - Patterns for creating and updating related models in django -
assuming have 2 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 give user form, on provide "name" of album, , have logic how create album photos given name. assumed need create 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 # common function creation , updating def update(self): # updating logic here # again common function creation , updating # additional unique logic updating def _update_only_method(self): # called on update def _common_logic(self): # common logic both create , update
and in views.py
im doing creation:
albumservice(album(name="user_provided_name")).create()
and updating:
albumservice(album.objects.get(pk=1)).update()
but confused, because, example, creation - dont need have list of photos (there no photo before creation) , method, used update not needed creation. - on each creation or updating - new instance of service created. i'm not satisfied behavior. maybe there useful patterns normalize such behavior?
upd
why haven't used managers? far know - managers "table-level" operations, here have several tables. updating of existing album "row-level" operation, should exist model method. think operations should coupled
Comments
Post a Comment