【发布时间】:2018-07-15 08:34:52
【问题描述】:
我的问题是关于在 Django-rest-framework api 的响应中获取 Django 查询结果。 我的 Django 项目中有以下产品、属性和产品选项模型:
class Product(models.Model):
productid = models.AutoField(db_column='productId', primary_key=True)
productname = models.CharField(db_column='productName', max_length=200)
class Attribute(models.Model):
attributeid = models.AutoField(db_column='attributeId', primary_key=True)
attributename = models.CharField(db_column='attributeName', max_length=200, blank=True, null=True)
class Productoptions(models.Model):
optionsid = models.AutoField(db_column='OptionsId', primary_key=True)
optionproductid = models.ForeignKey(Product, models.DO_NOTHING, db_column='optionProductId', blank=True, null=True)
optionattributeid = models.ForeignKey(Attribute, models.DO_NOTHING, db_column='optionAttributeId', blank=True, null=True)
我已经在所有三个表中填充了示例数据,当尝试获取属性名称为 nike 的产品时,以下 Django 查询在 Python shell 中完美运行。
Productoptions.objects.filter(optionattributeid__attributename='nike').values('optionproductid__productname')
得到结果
<QuerySet [{'optionproductid__productname': 'nike shirt'}, {'optionproductid__productname': 'nike tracksuit'}]>
但在我看来相关的模型类查询不起作用
class ProductOptionsView(APIView):
serializer_class = ProductOptionsSerializer
def get(self,request):
queryset = Productoptions.objects.filter(optionattributeid__attributename='nike').values('optionproductid__productname')
serializer = self.serializer_class(queryset, many=True)
return Response(serializer.data)
我没有从这个视图中得到想要的结果。有什么方法可以让所有 Django 查询简单地使用 Django-rest-framework 提供结果。所有 get 和 post 查询都可以在 Python shell 中完美运行。
有没有其他方法或者 DRF 有它自己的方法来使用嵌套模型导致 rest api。我也读过 Django Filter,但是 Django 的网站上没有文档。
【问题讨论】:
-
queryset在您的示例中未定义 -
我已经编辑了变量名称为查询集的问题。
-
尝试在最后删除
.values部分,以便将Django模型而不是python dicts传递给序列化器,然后根据需要调整序列化器中的输出 -
现在输出只从 Productoptions 表中获取数据。
-
是的,现在编辑序列化程序以输出您需要的内容
标签: python mysql django django-models django-rest-framework