这是我的第一篇文章,虽然我一直在搜索该网站。我找不到有其他人有这个问题的证据。django-tastypie使每个数据库查询两次
我有一个使用django-tastypie使用MySQL数据库后端构建的REST API。每次调用API(例如使用浏览器或angularJS前端)时,django-tastypie后端都会使每次数据库调用两次。
下面是从一个API调用Django的SQL记录器的输出:
(0.019) SELECT COUNT(*) FROM `products`; args=()
(0.020) SELECT `products`.`id` FROM `products` LIMIT 30; args=()
(0.023) SELECT (`product_styles`.`product_id`) AS `_prefetch_related_val`, `styles`.`id`, `styles`.`name` FROM `styles` INNER JOIN `product_styles` ON (`styles`.`id` = `product_styles`.`style_id`) WHERE `product_styles`.`product_id` IN (517, 518, 661, 662, 539, 429, 569, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 611, 597, 87, 88, 443, 509, 510, 511); args=(517, 518, 661, 662, 539, 429, 569, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 611, 597, 87, 88, 443, 509, 510, 511)
(0.020) SELECT COUNT(*) FROM `products`; args=()
(0.020) SELECT `products`.`id` FROM `products` LIMIT 30; args=()
(0.022) SELECT (`product_styles`.`product_id`) AS `_prefetch_related_val`, `styles`.`id`, `styles`.`name` FROM `styles` INNER JOIN `product_styles` ON (`styles`.`id` = `product_styles`.`style_id`) WHERE `product_styles`.`product_id` IN (517, 518, 661, 662, 539, 429, 569, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 611, 597, 87, 88, 443, 509, 510, 511); args=(517, 518, 661, 662, 539, 429, 569, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 611, 597, 87, 88, 443, 509, 510, 511)
的定时是不同的,但查询是相同的。我已通过登录MySQL确认重复查询实际上正在发生,它不仅仅是一个django日志记录问题。我还确认使用wireshark只发送一个http请求和响应(即,这不是因为我意外地发出两个API调用)。
我已将我的模型和资源代码切回到重现问题所需的裸骨,并将其包含在下面。任何人都可以提供一些关于如何进一步调查的想法吗?我很难过。
api.py
from tastypie.resources import ModelResource, Resource
from tastypie.fields import ToOneField, ToManyField
from FrameFish_aws.models import Product, ProductStyle, Style
class StyleResource(ModelResource):
class Meta:
queryset = Style.objects.all()
class ProductResource(ModelResource):
styles = ToManyField('FrameFish_aws.api.StyleResource', 'styles', full=True)
class Meta:
queryset = Product.objects.all().prefetch_related('styles')
resource_name = 'frames'
allowed_methods = ['get']
models.py
from django.db import models
class Style(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=300)
class Meta:
db_table = u'styles'
class ProductStyle(models.Model):
"""Intermediate table for holding associating styles with products"""
style = models.ForeignKey('Style', to_field='id')
product = models.ForeignKey('Product', to_field='id')
class Meta:
db_table = u'product_styles'
class Product(models.Model):
id = models.IntegerField(primary_key=True)
styles = models.ManyToManyField('Style', through='ProductStyle')
class Meta:
db_table = u'products'
根据[docs](https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related),select_related'仅限于单值关系 - 外键和一个-to-一个“。 – Pete 2013-03-20 22:18:45