用于状态检查的串行器
我有一个 Django 项目,其中有一家餐厅,有订单和桌子。您可以在模型下方看到:
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)
如果表仍在进行中,我应该限制创建新订单。我想这应该通过序列化器完成,但不知道验证以及如何将请求与数据库信息连接
当前序列化器(标准):
class OrdersModelSerializer(ModelSerializer):
class Meta:
model = Order
fields = "__all__"
当前视图:
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')
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')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
PrimaryKeyRelatedField
指定排除具有Order
的Table
的queryset=...
代码>状态='in_progress':You can specify the
queryset=…
of thePrimaryKeyRelatedField
that excludesTable
s for which there is anOrder
withstatus='in_progress'
: