AttributeError: 'Service' object has no attribute 'total_views'
I'm putting a ManyToManyField with a related_name and when I make queries it just doesn't recognize the related_name. I even tried without the related_name and it didn't work anyway.
The model:
from ipadresses.models import UsersIpAddresses
class Service(models.Model):
title = models.CharField(max_length=50, unique=True, blank=False, null=False)
slug = models.SlugField(editable=False, unique=True, blank=False, null=False)
description = models.TextField(max_length=200, blank=False, null=False)
main_image = models.CharField(max_length=200, blank=False, null=False)
url = models.CharField(max_length=500, editable=False, unique=True, blank=False, null=False)
ip_addresses_views = models.ManyToManyField(to=UsersIpAddresses, related_name="total_views",)
def __str__(self):
return self.title
def save(self, *args, **kwargs) -> None:
self.slug = slugify(self.title)
self.url = f"/{self.slug}"
self.main_image = f"img/{self.main_image}"
return super().save(*args, **kwargs)
The view:
class ServicesRetrieveView(RetrieveAPIView):
serializer_class = ServiceSerializer
def get_queryset(self, slug):
try:
return Service.objects.get(slug=slug)
except ObjectDoesNotExist:
raise Http404
def get(self, request, slug):
serializer = self.serializer_class(self.get_queryset(slug=slug), many=False).data
serializer["products"] = ProductSerializer(self.get_queryset(slug=slug).product_set.all()[::-1], many=True).data
if request.user.is_authenticated:
for product in serializer["products"]:
product["message_for_queries"] = Product.message_for_queries(user_name=request.user.username, product_name=product["title"])
try:
# UsersIpAddresses.objects.get(request.META["REMOTE_ADDR"])
query_set = self.get_queryset(slug=slug)
query_set.total_views.get(ip = request.META["REMOTE_ADDR"])
except ObjectDoesNotExist:
# UsersIpAddresses.objects.create(ip = request.META["REMOTE_ADDR"])
ip = None
try:
ip = UsersIpAddresses.objects.get(request.META["REMOTE_ADDR"])
except ObjectDoesNotExist:
ip = UsersIpAddresses(ip=request.META["REMOTE_ADDR"])
ip.save()
self.get_queryset(slug=slug).total_views.add(ip)
print(len(self.get_queryset(slug=slug).total_views.all()))
return Response(data=serializer, status=200)
the exception:
AttributeError at /services/diseno-grafico/
'Service' object has no attribute 'total_views'
I really don't get why this is happenig.