如何在 DRF 序列化程序中检查条件,然后跳过该迭代并转到下一个迭代



我有一个序列化程序,如下所示:

class CustomerSerializer(serializers.ModelSerializer):
product = serializers.SerializerMethodField()
def get_product(self, obj):
obj.product = Customer.check_is_product(obj.product_id)
return obj.product.name
class Meta:
model = Customer
fields = ['name', 'product']

我有一个 models.py 如下:

class Product(models.Model):
name = models.IntegerField()
class Meta:
db_table = 'products'

class Customer(models.Model):
name = models.CharField(max_length=255)
product_id = models.IntegerField()
class Meta:
db_table = 'customers'
@staticmethod
def check_is_product(id)
try:
product_obj = Products.objects.get(id=id)
except:
<if product with that id isn't there, then i wanna skip that iteration in serializer>
return product_obj

现在假设我的数据库中有三个客户,其中一个客户没有任何产品,然后我想在我的 API 响应中跳过整个客户的详细信息。所以我的最终 API 响应将有一个只有 2 个项目的列表。有谁知道如何在任何条件检查中跳过序列化程序的迭代?

您可以在视图中处理逻辑。

选项 1:为该类型的请求创建自定义视图。
选项 2:将查询参数作为该类型请求的标志发送到当前视图。
选项 3:只需使用逻辑编辑当前视图即可根据需要进行筛选。

选项 1 的示例,它将返回一个查询集,其中包含产品 ID 大于 0 的所有客户:

queryset = Customer.objects.all(product_id__gt=0)

另外,在Customer.product_id,我建议从模型切换。IntergerField(( 到模型。外键(产品,on_delete=型号。保护,空=真,空白=真(。

编辑:更深入的答案,编辑视图集以获取所需的查询集。

class CustomerViewSet(viewsets.ModelViewSet):
serializer_class = CustomerSerializer
def get_queryset(self):
queryset = Customer.objects.all(product_id__gt=0)
return queryset

相关内容

最新更新