这是我的第一篇文章,虽然我一直在搜索网站。我找不到其他人有这个问题的证据。
我有一个使用MySQL数据库后端使用django-tastypie构建的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'
答案 0 :(得分:1)
我自己找到了答案。我还在运行django-debug-toolbar中间件。我没有意识到它由re-executing every sql query起作用...因此重复查询。