简体   繁体   中英

Filtering in serializers Django rest framework

In my project, a room has different statuses, for example: registered, available, each status has a start date, I have to get the start_date when the status is registered. how can I do that in serializer? Thanks in advance!

in model.py:

 class RoomStatus(models.Model):
  room = models.ForeignKey(Room, on_delete=models.DO_NOTHING, related_name='rooms')

  class RoomStatusChoices(models.IntegerChoices):
    REGISTERED = 1
    RESERVED = 2
    AVAILABLE = 3


  room_status = models.SmallIntegerField(choices=RoomStatusChoices.choices, default=RoomStatusChoices.AVAILABLE)
  start_date = models.DateTimeField(default=timezone.now())

In serializers.py:

 class RoomStatusSerializer(serializers.ModelSerializer):
    class Meta:
        model = RoomStatus
        fields = ['id', 'start_date']

 class RoomSerializer(serializers.ModelSerializer):
  rooms = RoomStatusSerializer(many=True)

   class Meta:
     model = Room
     fields = ['id', 'rooms']   

in views.py:

 class RoomViewSet(RetrieveModelMixin, ListModelMixin, GenericViewSet, UpdateModelMixin):
   queryset = Room.objects.all()
   serializer_class = RoomSerializer

If I understood correctly, you can do something like this:

Important notes however:

  • You have to handle the case where RoomStatus with room=pk or status=1 does not exist.
  • If your model RoomStatus does not have a unique constraint for room and room_status you have to handle the case where there are multiple objects return which will raise an error when using .get()
from .models import RoomStatus

class RoomSerializer(serializers.ModelSerializer):
    register_date = serializers.SerializerMethodField()

    def get_register_date(self, obj):
        return RoomStatus.objects.get(room=obj.pk, room_status=1).start_date

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