【问题标题】:Filtering by ForeignKey with a legacy model doesn't work without .pk如果没有 .pk,使用旧模型按 ForeignKey 过滤不起作用
【发布时间】:2011-01-25 00:33:08
【问题描述】:

我有一个旧数据库,我设置了一些要使用的模型。模型如下所示:

class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True, db_column='uid')
    email = models.CharField(max_length=255, unique=True)
    username = models.CharField(unique=True, max_length=150)
    class Meta:
        db_table = u'legacy_user'

class OtherModel(models.Model):
    user = models.ForeignKey('my_app.UserProfile', db_column='uid')
    some_data = models.IntegerField()
    another_model = models.ForeignKey('other_app.AnotherModel', db_column='related')
    class Meta:
        db_table = u'legacy_other_model'

当我执行这个查询集时:

my_user = UserProfile.objects.get(username='foo')
count = OtherModel.objects.filter(user=my_user).count()

我得到的 SQL 看起来像:

SELECT COUNT(*) FROM `legacy_other_model` WHERE `legacy_other_model`.`uid` = None

但如果我将计数查询更改为此(注意 .pk):

count = OtherModel.objects.filter(user=my_user.pk).count()

我得到的 SQL 看起来像:

SELECT COUNT(*) FROM `legacy_other_model` WHERE `legacy_other_model`.`uid` = 12345

这似乎不是预期的行为,查看:http://docs.djangoproject.com/en/dev/topics/db/queries/#queries-over-related-objects

我是否在模型中设置了错误?

【问题讨论】:

  • 只是一个松散的猜测——也许那些对相关对象的查询是错误的,因为他们假设主键总是id。如果没有人回答这个问题,您可以检查 Django 错误跟踪器中是否报告了类似的内容。

标签: django django-models django-queryset


【解决方案1】:

怀疑您可能需要在 OneToOne 定义中指定 to_field

user = models.ForeignKey('my_app.UserProfile', db_column='uid', to_field='user')

这有帮助吗?

【讨论】:

  • to_field 默认为相关模型的主键。指定它没有帮助 - 它仍然在 SQL 中放置“无”。
【解决方案2】:

在这一点上,我相信这是 Django 中的一个错误。

为了将来参考,我在这里报告了它: http://code.djangoproject.com/ticket/15164

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    • 2021-12-29
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 2020-01-19
    • 1970-01-01
    相关资源
    最近更新 更多