Why is it getting objects for province but not for city when the city is in the province

I have a Django project and the following models for a location that is attached to a business in this case and related as branches:

class Province(models.Model):
    name = models.CharField(max_length=50)
    created_at = models.DateTimeField("date post was created", auto_now_add=True)
    updated_at = models.DateTimeField("date post was updated", auto_now=True)

    class Meta:
        verbose_name = "province"
        verbose_name_plural = "provinces"
        db_table = "provinces"
        ordering = ["name"]

    def __str__(self):
        return self.name


class City(models.Model):
    name = models.CharField(max_length=50)
    province = models.ForeignKey(Province, on_delete=models.CASCADE, default=None, related_name="cities")
    created_at = models.DateTimeField("date post was created", auto_now_add=True)
    updated_at = models.DateTimeField("date post was updated", auto_now=True)

    class Meta:
        verbose_name = "city"
        verbose_name_plural = "cities"
        db_table = "cities"
        ordering = ["name"]
        unique_together = ('name', 'province',)

    def __str__(self):
        return self.name


class Area(models.Model):
    name = models.CharField(max_length=50)
    city = models.ForeignKey(City, on_delete=models.CASCADE, default=None, related_name="areas")
    zip_code = models.CharField(max_length=30)
    created_at = models.DateTimeField("date post was created", auto_now_add=True)
    updated_at = models.DateTimeField("date post was updated", auto_now=True)

    class Meta:
        verbose_name = "area"
        verbose_name_plural = "areas"
        db_table = "areas"
        ordering = ["name"]

    def __str__(self):
        return self.name


class Location(models.Model):
    name = models.CharField(max_length=50, null=True, blank=True)
    complex = models.CharField(max_length=50, null=True, blank=True)
    street = models.CharField(max_length=100, null=True, blank=True)
    additional = models.CharField(max_length=100, null=True, blank=True)
    area = models.ForeignKey(Area, on_delete=models.SET_DEFAULT, default=1, related_name="profile_locations")
    phone = models.CharField(max_length=15, null=True, blank=True)
    whatsapp = models.CharField(max_length=15, null=True, blank=True)
    fax = models.CharField(max_length=15, null=True, blank=True)
    mobile = models.CharField(max_length=15, null=True, blank=True)
    email = models.EmailField(null=True, blank=True)
    latitude = models.CharField(max_length=15, null=True, blank=True)
    longitude = models.CharField(max_length=15, null=True, blank=True)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="location", null=True, blank=True)
    business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name="branches", null=True, blank=True)
    event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name="venues", null=True, blank=True)
    opportunity = models.ForeignKey(Opportunity, on_delete=models.CASCADE, related_name="locations", null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at")

    class Meta:
        verbose_name = "location"
        verbose_name_plural = "locations"
        db_table = "locations"
        ordering = ["area"]

    def __str__(self):
        if self.name:
            return self.name
        if self.profile:
            return f"{self.profile}"
        if self.business:
            return f"Business: {self.business}"
        if self.event:
            return f"Event: {self.event}"
        if self.opportunity:
            return f"Opportunity: {self.opportunity}"
        return "Location"

The problem is with the following DRF view to filter businesses by location. It works for filtering by province but city it returns no objects when in fact the city is in the province that finds a business object when I filter it.

here is the view:

class ListBusinessByLocation(generics.ListAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = ListBusinessesSerializer

    def post(self, request, *args, **kwargs):
        location_id = request.data.get('id')  
        location_type = request.data.get('type') 
        
        queryset = Business.objects.all()

        if not location_id or not location_type:
            return Response({"error": "Both 'id' and 'type' are required."}, status=HTTP_400_BAD_REQUEST)

        if location_type == 'area':
            try:
                area = Area.objects.get(pk=location_id)
                queryset = queryset.filter(branches__area=area).distinct()
                return self.get_response(queryset)
            except Area.DoesNotExist:
                return Response({"error": "Area not found."}, status=HTTP_404_NOT_FOUND)

        elif location_type == 'city':
            breakpoint()
            try:
                city = City.objects.get(pk=location_id)
                queryset = queryset.filter(branches__area__city=city).distinct()
                return self.get_response(queryset)
            except City.DoesNotExist:
                return Response({"error": "City not found."}, status=HTTP_404_NOT_FOUND)

        elif location_type == 'province':
            try:
                province = Province.objects.get(pk=location_id)
                queryset = queryset.filter(branches__area__city__province=province).distinct()
                return self.get_response(queryset)
            except Province.DoesNotExist:
                return Response({"error": "Province not found."}, status=HTTP_404_NOT_FOUND)

        return Response({"error": "Invalid location type."}, status=HTTP_400_BAD_REQUEST)

    def get_response(self, queryset):
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

Can anybody tell me where I am making a mistake please?

Вернуться на верх