Django “Lookups that span relationships” Error

好久不见. 提交于 2019-12-11 13:38:58

问题


I'm trying to follow the documentation for lookups that span relationships for a "reverse" relationship, found here. Here is my model code:

class Foo(models.Model):
    initiator = models.ForeignKey(User)
    date_time = models.DateTimeField()
    ...

And here is my query code:

...   
now = datetime.now()
users = User.objects.filter(foo__date_time__gte = now)
...

This results in the following error: django.core.exceptions.FieldError: Cannot resolve keyword 'foo' into field. Choices are: _message_set, date_joined, email, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, user_permissions, username

However, if I change my code to not use User, but instead use my own model type Bar, then everything works as I would expect with no errors. Example below:

class Foo(models.Model):
    initiator = models.ForeignKey(Bar)
    date_time = models.DateTimeField()
    ...

...   
now = datetime.now()
bars = Bar.objects.filter(foo__date_time__gte = now)
...

Can anyone explain to me the problem with the first code that uses the User model as the foreign key? Thanks in advance!

EDIT: I should clarify that my query code is not in a view function, but in a utility function that I call using a manage.py command. If I put the query code in a view then everything works fine with no errors! But the curious thing is that the second code example works fine in both the view and the management command scenarios.

Hopefully someone with a little more Django expertise than me can explain this. Thanks!


回答1:


Ok, problem solved! This seems like an incredibly minute detail that was causing this issue, and I can't say I fully understand why it manifested like it did, but here goes:

I had from django.contrib.auth.admin import UserAdmin at the top of my models.py, along with my other import statements. This was actually left over from before I refactored out my admin stuff into its own admin.py, so the UserAdmin import was not being used at all in models.py. I commented out this unused statement, then did a syncdb and got a model validation error on a reverse query name that clashed (this was in a ForeignKey field in my User Profile model, but not the model I couldn't query in my original question). So I added a related_name argument to that field, did a syncdb, executed my original query that was giving errors previously, and everything worked error-free!

So in the end it boiled down to an errant from django.contrib.auth.admin import UserAdmin.

Thank you to all who responded trying to help!



来源:https://stackoverflow.com/questions/6407119/django-lookups-that-span-relationships-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!