I have a legacy database that I've set up some models to use. The models look开发者_运维知识库 like this:
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'
When I perform this queryset:
my_user = UserProfile.objects.get(username='foo')
count = OtherModel.objects.filter(user=my_user).count()
I get SQL that looks like:
SELECT COUNT(*) FROM `legacy_other_model` WHERE `legacy_other_model`.`uid` = None
But if I change the count query to this (note the .pk):
count = OtherModel.objects.filter(user=my_user.pk).count()
I get SQL that looks like:
SELECT COUNT(*) FROM `legacy_other_model` WHERE `legacy_other_model`.`uid` = 12345
This doesn't seem to be the expected behavior, looking at: http://docs.djangoproject.com/en/dev/topics/db/queries/#queries-over-related-objects
Did I set up something wrong in my models?
Suspect you might need to specify to_field
on your OneToOne definition:
user = models.ForeignKey('my_app.UserProfile', db_column='uid', to_field='user')
Does that help?
At this point, I believe this is a bug in Django.
For future reference, I've reported it here: http://code.djangoproject.com/ticket/15164
精彩评论