Home > OS >  Serializer for status check
Serializer for status check

Time:02-26

I have a Django project where a restaurant with orders and tables. You can see below the model:

class Order(models.Model):
    STATUS_CHOICES = (
        ("in_progress", "In_progress"),
        ('completed', 'Completed')
    )
    table = models.ForeignKey(Table, on_delete=models.CASCADE, blank=False, null=False, related_name='order_table')
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=False, null=False, related_name='order_user')
    status = models.CharField(choices=STATUS_CHOICES, null=True, max_length=15)

I should restrict creating a new order if the table is still in progress. I guess it should be done through serializer but hove no idea about the validation and how to connect request with database information

current serializer (standard):

class OrdersModelSerializer(ModelSerializer):
    class Meta:
        model = Order
        fields = "__all__"

current view:

class OrdersFilter(filters.FilterSet):
    class Meta:
        model = Order
        fields = (
            'user', 'table__id', 'status',
        )


class OrdersModelViewSet(ModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrdersModelSerializer
    pagination_class = LimitOffsetPagination   
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    filter_class = OrdersFilter
    ordering_fields = ('table', 'user', 'status')

CodePudding user response:

You can specify the queryset=… of the PrimaryKeyRelatedField that excludes Tables for which there is an Order with status='in_progress':

from rest_framework import serializers

class OrdersModelSerializer(ModelSerializer):
    table = serializers.PrimaryKeyRelatedField(
        queryset=Table.objects.exclude(order_table__status='in_progress')
    )
    
    class Meta:
        model = Order
        fields = '__all__'

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

  • Related