这是我的第一篇文章,尽管我一直在搜索该网站。我找不到其他人有这个问题的证据。
我有一个使用 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']
模型.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'