【发布时间】:2010-12-13 01:59:01
【问题描述】:
这是我的 django 模型:
class Author (models.Model):
name = models.CharField(max_length=255)
removed = models.BooleanField(default=False)
class Image (models.Model):
author = models.ForeignKey(Author)
name = models.CharField(max_length=255)
height = models.PositiveIntegerField()
width = models.PositiveIntegerField()
基本上,我需要选择每个未删除且具有 5 个或更少高度等于 100 的图像的作者。
我用的是 MySQL,这里是版本信息:
mysql Ver 14.12 Distrib 5.0.67
自然是这样的:
Author.objects.filter(removed=False).extra(select={
'imgcount': """SELECT COUNT(*)
FROM ormtest_image
WHERE height=100 AND
ormtest_image.author_id=ormtest_author.id"""
}).filter(imgcount__lte=5)
它不起作用:“FieldError: Cannot resolve keyword 'imgcount' into field。选项有:id、image、name、removed”
好的,我们试试额外方法的 where 参数:
Author.objects.filter(removed=False).extra(select={
'imgcount': """SELECT COUNT(*)
FROM ormtest_image
WHERE height=100 AND
ormtest_image.author_id=ormtest_author.id"""
}, where=['imgcount <= 5'])
它也不起作用:“OperationalError: (1054, "Unknown column 'imgcount' in 'where Clause'")”,因为要过滤 MySQL 中计算字段的数据,您必须使用 HAVING 子句。
有什么想法吗?
我使用 Django 1.1 和来自 trunk 的最新版本对此进行了测试。
到目前为止,我使用这个 hack:
Author.objects.filter(removed=False).extra(select={
'imgcount': """SELECT COUNT(*)
FROM ormtest_image
WHERE height=100 AND
ormtest_image.author_id=ormtest_author.id"""
}, where=['1 HAVING imgcount <=5'])
附: YAML 夹具:
---
- model: ormtest.author
pk: 1
fields:
name: 'Author #1'
removed: 0
- model: ormtest.author
pk: 2
fields:
name: 'Author #2'
removed: 0
- model: ormtest.author
pk: 3
fields:
name: 'Author #3'
removed: 1
- model: ormtest.image
pk: 1
fields:
author: 1
name: 'Image #1'
height: 100
width: 100
- model: ormtest.image
pk: 2
fields:
author: 1
name: 'Image #2'
height: 150
width: 150
- model: ormtest.image
pk: 3
fields:
author: 2
name: 'Image #3'
height: 150
width: 100
- model: ormtest.image
pk: 4
fields:
author: 2
name: 'Image #4'
height: 150
width: 150
【问题讨论】:
标签: django django-models