I have an ecommerce store app that have those apps:
- core: specific for the ecommerce store app needs.
- likes: independent reusable app that is supposed to be used with different models from other apps.
- store: independent reusable app that has the models and views for the ecommerce app.
Now I want to add the ability for the user to like a product, so I want to add a like (from likes) to the product (from store), how can I do it without adding explicit dependency (import likes in store) between the two apps?
The LikedItem
model from likes app
:
from django.conf import settings
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
class LikedItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
The Product
model from the store app
:
class Product(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
description = models.TextField(null=True, blank=True)
unit_price = models.DecimalField(
max_digits=6,
decimal_places=2,
validators=[MinValueValidator(1)])
inventory = models.IntegerField(validators=[MinValueValidator(0)])
last_update = models.DateTimeField(auto_now=True)
collection = models.ForeignKey(
Collection, on_delete=models.PROTECT, related_name='products')
promotions = models.ManyToManyField(Promotion, blank=True)
def __str__(self) -> str:
return self.title
class Meta:
ordering = ['title']
I tried implementing this in the core app, I started with creating a CustomProduct model that extends the Product model and adds likes = GenericRelation(LikedItem)
, but things became messy in the serializer part, as I couldn’t extend the Product serializer and add the likes field to it, and I felt that I may need to completly implement the Product model only in the core app.