1
votes

I'm using Django REST 2.2 with rest-auth.

I have a custom user model with an additional field "custom_field". I'm trying to select all users where custom_field="something".

However when I browse to /api/accounts I'll get the following error: "django.core.exceptions.FieldError: Cannot resolve keyword 'custom_field' into field. Choices are: auth_token, course, date_joined, email, emailaddress, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, socialaccount, user_permissions, username, userprofile"

So it seems like my custom_field is not recognized. What did I do wrong?

user_profile/models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    customField = models.CharField(max_length=255, blank=True, null=True)

user_profile/serializers.py

class UserSerializer(UserDetailsSerializer):

    custom_field = serializers.CharField(source="userprofile.custom_field", allow_blank=True, required=False)

    class Meta(UserDetailsSerializer.Meta):
        fields = UserDetailsSerializer.Meta.fields + ('custom_field')

def update(self, instance, validated_data):
    custom_field = profile_data.get('custom_field')

    instance = super(UserSerializer, self).update(instance, validated_data)

    # get and update user profile
    profile = instance.userprofile
    if profile_data:
        if custom_field:
            profile.custom_field = custom_field
        profile.save()
    return instance

user_profile/views.py

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def list(self, request):
        queryset = User.objects.filter(custom_field="something")
        serializer = UserSerializer(queryset, many=True)
        return Response(serializer.data)

project/urls.py

router = routers.DefaultRouter()
router.register('accounts', UserViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),

    # This is used for user reset password
    path('', include('django.contrib.auth.urls')),
    path('rest-auth/', include('rest_auth.urls')),
    path('rest-auth/registration/', include('rest_auth.registration.urls')),
    path('account/', include('allauth.urls')),
    path('api/',  include(router.urls)),

rest_auth/serializers.py (dependency)

class UserDetailsSerializer(serializers.ModelSerializer):
    """
    User model w/o password
    """
    class Meta:
        model = UserModel
        fields = ('pk', 'username', 'email', 'first_name', 'last_name')
        read_only_fields = ('email', )
1
Should it be User.objects.filter(userprofile__custom_field="something") instead of User.objects.filter(custom_field="something") ? As specified in docs.djangoproject.com/en/3.0/topics/db/examples/one_to_oneLewis
The custom_field filed is defined in UserProfile model and you are trying to add the same field in a ModelSerializer, which is supposed to serialize the User model objects. Similar thing in filtering the objectsJPG
As Lewis mentioned, it should be .filter(userprofile__custom_field="something")JPG
@LewisHepburn If you want you can make an answer and I'll approve it.SJ19
Thank you @ArakkalAbu! Problem solved.SJ19

1 Answers

1
votes

When filtering on a OnetoOneField, the associated partner model must be referenced in the query.

User.objects.filter(userprofile__custom_field="something")

Notice how userprofile__ is included in the filter.

More information on on filter lookups can be found here