我知道我不是第一个提出这个问题的人,但我无法找到解决方案。我有以下型号:
class Size(models.Model):
id = models.IntegerField()
size = models.CharField(max_length=255)
country = models.CharField(max_length=255)
class Meta:
db_table = 'size'
class Orders(models.Model):
id = models.IntegerField()
order_id = models.CharField(max_length=255)
date = models.DateTimeField()
status = models.CharField(max_length=1)
brand_id = models.IntegerField()
user_id = models.IntegerField()
shop_id = models.IntegerField()
item_id = models.IntegerField()
category_id = models.IntegerField()
item_gender = models.CharField(max_length=1)
return_reason = models.CharField(max_length=255)
size = models.ForeignKey(Size)
class Meta:
db_table = 'orders'
我尝试使用反向查找,因为它描述了this
sizes = Size.objects.using('mysql_db').filter(orders__user_id=6)
错误:
Cannot resolve keyword 'orders' into field. Choices are: country, id, size
Request Method: GET
Request URL: http://127.0.0.1:8000/dictionary/types/
Django Version: 1.8.2
Exception Type: FieldError
Exception Value:
Cannot resolve keyword 'orders' into field. Choices are: country, id, size
Exception Location: /Users/.../env/lib/python3.4/site-packages/django/db/models/sql/query.py in names_to_path, line 1391
Python Executable: /Users/.../env/bin/python
Python Version: 3.4.3
答案 0 :(得分:0)
我已经验证您发布的查询是按原样运行的,问题出在代码的其他位置。你运行makemigrations并迁移吗?您可以找到工作代码示例here:
models.py
from django.db import models
# Create your models here.
class Size(models.Model):
id = models.IntegerField(primary_key=True)
size = models.CharField(max_length=255)
country = models.CharField(max_length=255)
class Meta:
db_table = 'size'
class Orders(models.Model):
id = models.IntegerField(unique=True,primary_key=True)
order_id = models.CharField(max_length=255)
date = models.DateTimeField()
status = models.CharField(max_length=1)
brand_id = models.IntegerField()
user_id = models.IntegerField(default = 6)
shop_id = models.IntegerField()
item_id = models.IntegerField()
category_id = models.IntegerField()
item_gender = models.CharField(max_length=1)
return_reason = models.CharField(max_length=255)
size = models.ForeignKey(Size)
class Meta:
db_table = 'orders'
views.py
class ReverseFK(ListView):
model = Size
def get_queryset(self):
Size.objects.create()
return Size.objects.filter(orders__user_id=5)
答案 1 :(得分:0)
变种之一
sizes = [item.size for item in Orders.objects.filter(user_id=6)]
但是,您应该使用select_related
将SQL查询量减少到一个。
否则您将隐式执行n + 1次查询。