OneToOne 关系和 django-autocomplete-light

OneToOne relationship and django-autocomplete-light

我有一些关于 django-autocomplete-light 的问题,我无法自行解决。

models.py

from django.contrib.auth.models import User
class UserProfile(models.Model):    
   user = models.OneToOneField(User, related_name="user_profile")
   ...

autocomplete_light_registry.py

class UserProfileAutocomplete(autocomplete_light.AutocompleteModelBase):
    model = UserProfile
    search_fields = ['username']
    attrs = {
        'data-autocomplete-minimum-characters': 1,
    }

autocomplete_light.register(UserProfileAutocomplete)

我试过了,但出现错误:FieldError,无法将关键字 u'username' 解析为字段。

我已经尝试过 "user" 但它引发了:TypeError,相关字段查找无效:​​icontains

我该怎么办?

非常感谢。

您需要用户模型的 username。所以你需要 user__username

class UserProfileAutocomplete(autocomplete_light.AutocompleteModelBase):
    model = UserProfile
    search_fields = ['user__username'] # <-- user__username instead username
    attrs = {
       'data-autocomplete-minimum-characters': 1,
    }

    autocomplete_light.register(UserProfileAutocomplete)