【发布时间】: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