Django ORM在SQL Join中创建Phantom Alias

时间:2009-06-18 16:39:24

标签: mysql django join django-orm mysql-error-1054

我正在执行以下代码(更改名称以保护无辜,因此模型结构可能看起来很奇怪):

memberships = 
    models.Membership.objects.filter(
        degree__gt=0.0,
        group=request.user.get_profile().group
    )

exclude_count =  
    memberships.filter(
        member__officerships__profile=request.user.get_profile()
    ).count()

if exclude_officers_with_profile:
    memberships = memberships.exclude(
        member__officerships__profile=request.user.get_profile()
    )

total_count = memberships.count()

此时会产生:

OperationalError at /
(1054, "Unknown column 'U1.id' in 'on clause'")

生成的SQL是:

SELECT 
    COUNT(*) 
FROM 
    `membership` 
WHERE (
    `membership`.`group_id` = 2 AND
    `membership`.`level` > 0.0 AND 
    NOT (
        `membership`.`member_id` 
        IN (
            SELECT 
                U2.`member_id` 
            FROM 
                `membership` U0 INNER JOIN `officers` U2 
                ON (U1.`id` = U2.`member_id`) 
            WHERE U2.`profile_id` = 2 
        )
    )
)

似乎SQL Join的ON语句引用了尚未定义的别名。任何想法为什么!?我删除了我的MySQL数据库并重新同步了我的模型中的表格,以确保那里没有任何不一致。

我正在使用的模型的结构是:

class Membership(models.Model):
    member = models.ForeignKey(Member, related_name='memberships')
    group = models.ForeignKey(Group, related_name='memberships')
    level = models.FloatField(default=0.0)

class Member(models.Model):
    name = models.CharField(max_length=32)

class Officer(models.Model):
    member = models.ForeignKey(Member, related_name='officerships')
    profile = models.ForeignKey(UserProfile)

class UserProfile(models.Model)
    group = models.ForeignKey(Group)

class Group(models.Model)
    pass

1 个答案:

答案 0 :(得分:1)

我认为这可能是以下症状:

http://code.djangoproject.com/ticket/9188

我认为,已经修改了django修订版9589。现在如何确定我正在使用哪个版本...


确认。当我实现上面故障单中引用的更改时:

http://code.djangoproject.com/changeset/9589

我的错误消失了。