简体   繁体   中英

drf viewset : multiple choices

I tried to make method(location_item) that shows item by region. And I want to implement the 'gu, dong' field(in location model) with multiple choices. so, wrote this method code. but filtering doesn't work.. This shows all item objects, not just the objects I want.

TypeError: Field 'id' expected a number but got <Item: 애니원모어 원피스입니다.>: [13/Aug/2022 15:01.07] "GET /item_post/location/location_item/ HTTP/1.1" 500 152955

I don't know what sholud i do. please help me...

models.py

class Item(models.Model):
    user_id = models.ForeignKey(User, related_name='item_sets', on_delete=models.CASCADE)
    category_id = models.ForeignKey(Category, related_name='item_sets', on_delete=models.DO_NOTHING)
    description = models.TextField()
    feature = models.TextField()
    product_defect = models.TextField()
    size = models.CharField(max_length=6)
    wear_count = models.IntegerField()
    price = models.IntegerField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.description


class Location(models.Model):
    city = models.CharField(max_length=10)
    gu = models.CharField(max_length=10)
    dong = models.CharField(max_length=10)

    def __str__(self):
        return self.city+" "+self.gu+" "+self.dong


class LocationSet(models.Model):
    item_id = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='location_sets')
    location_id = models.ForeignKey(Location, on_delete=models.CASCADE, related_name='location_sets')

serializers.py

class ItemSerializer(serializers.ModelSerializer):
    photos = PhotoSerializer(source='photo_sets', many=True, read_only=True)
    style_photos = StylePhotoSerializer(source='style_photo_sets', many=True, read_only=True)

    class Meta:
        model = Item
        fields = '__all__'


class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = '__all__'


class LocationSetSerializer(serializers.ModelSerializer):
    class Meta:
        model = LocationSet
        fields = '__all__'

views.py

class ItemViewSet(ModelViewSet):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer
    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['description']    # ?search=
    ordering_fields = ['-created_at']  # ?ordering=
    ordering = ['-created_at']

    # here
    @action(detail=False, methods=['GET'])
    def location_item(self, request):
        locations = Location.objects.all()
        city = request.GET.get('city', None)  
        gu = request.GET.getlist('gu', None)  # multiple choices
        dong = request.GET.getlist('dong', None)  # multiple choices
        print(city, " ", gu, " ", dong)  # > None   []   [] (upper codes not work..)
        if city:
            locations = locations.filter(city=city)
        if gu:
            locations = locations.filter(gu__in=gu).distinct()
        if dong:
            locations = locations.filter(dong__in=dong).distinct()

        location_ids = []
        for i in locations:
            location_ids.append(i.id)

        locationsets = LocationSet.objects.filter(location_id__in=location_ids)

        item_ids = []
        for i in locationsets:
            item_ids.append(i.item_id)
        serializer = self.get_serializer(item_ids, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

To create method that shows items by region. what sholud i do?

I think the last lines of code are wrong.

...

@action(detail=False, methods=['GET'])
def location_item(self, request):
    ...

    # here I changed the last four lines
    item_ids = [x.item_id for x in locationsets]
    serializer = self.get_serializer(item_id__id__in = item_ids, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM