I'm trying to solve what looked like an easy problem at first to me and probably I'm overthinking it, but I'm unsure where to put the bit of logic required, so any input would be much appreciated.
Following situation (example code, not real project)
# models.py
class Product(models.Model):
title = models.CharField()
price_in_cents = models.IntegerField()
# ...
class ProductImage(models.Model):
product = models.ForeignKey('Product', null=True, blank=True)
image = models.ImageField()
user = models.ForeignKey(get_user_model())
# ...
So in short I have products and images that show these products. This is part of a DRF project which is consumed by a Vue frontend.
The flow is as follows:
- The client creates new images by posting the image data to /api/productimages/
- The API creates the Image instance and returns the data including the created instances PK.
- The client then posts a list of image ids along with the data to create the product to /api/products/
- the api creates the product and should now associate the passed images with the created product. This should only happen if current user == image.user and image.product is not set yet (==Null)
Now my question: Where should I put the logic to associate the images with the created product? I see the following possibilities:
- In the view (controller). Easy for this use-case, but I don't think that's the right place.
- In a separate service layer. More clean, but still has to be called from view
- Image Model. Would be cleaner, but I'm unsure how to implement the conditions when doing this in the model.
Thanks!
Aucun commentaire:
Enregistrer un commentaire