hey guys i don't know if what i am doing is right but i have these class or model
class CartItem(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.UUIDField()
content_object = GenericForeignKey('content_type','object_id')
and i have this related model using the generic foreign key
class MstProduct(PhysicalProduct):
user = models.ForeignKey(User, models.PROTECT)
purposes = models.ManyToManyField(ProductPurpose, null = True, blank = True, related_name='products')
madeOf = models.ManyToManyField(AffeliateProduct, null = True, blank = True)
category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name = "physical_products")
theme = models.ForeignKey(Theme, on_delete= models.SET_NULL, null = True, blank = True, related_name = 'physical_products')
art_type = models.ForeignKey(ArtType, on_delete=models.SET_NULL, null = True,blank = True)
cart_items = GenericRelation(CartItem,related_query_name='product')
what i wanna do is to access the product related to CartItem instance from the generic foreign key field, i tried to do it using the related_query_name argument but after trying this:
CartItem.objects.first().product
I get an error like this:
Traceback (most recent call last):
File "/home/alaa/.local/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 678, in get_queryset
return self.instance._prefetched_objects_cache[
AttributeError: 'CartItem' object has no attribute '_prefetched_objects_cache'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/alaa/.local/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/alaa/.local/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 683, in get_queryset
return self._apply_rel_filters(queryset)
File "/home/alaa/.local/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 640, in _apply_rel_filters
val = getattr(self.instance, field.attname)
AttributeError: 'CartItem' object has no attribute 'productId'
productId is basically a field of this abstract class:
class Product(models.Model):
productId = models.UUIDField(default=uuid4, primary_key=True, editable=False)
picture = models.ImageField()
discription = models.TextField(max_length=2000)
price = models.FloatField()
orders = GenericRelation(Order, related_query_name='orders')
createdAt = models.DateTimeField(auto_now_add=True)
updatedAt = models.DateTimeField(auto_now=True)
rates = GenericRelation(ProductRate,related_query_name='rates')
themes = GenericRelation(Theme)
purchase_num = models.PositiveBigIntegerField()
I am confused a bit here, if anyone can help i would really appreciate it
According to the docs, try.