question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

expression has type "SlugRelatedField[<nothing>]"

See original GitHub issue

I have the following serializer:

class ReportConfigurationSerializer(serializers.ModelSerializer[ReportScheduleConfiguration]):
    created_by = serializers.SlugRelatedField(read_only=True, slug_field="email")
    generation_settings = ReportGenerationSettingsJSONField(read_only=True)
    send_time_zone = TimeZoneSerializerField()

    class Meta:
        model = ReportScheduleConfiguration
        fields = (
            "id",
            "name",
            "send_time",
            "send_time_zone",
            "recipients",
            "report_type",
            "generation_settings",
        )

I would expect that mypy can detect the type of created_by, instead I have the error: Need type annotation for 'created_by' [var-annotated]

If I add a type annotation just for example eg: created_by: str = serializers.SlugRelatedField(read_only=True, slug_field="email") The error updates to: Incompatible types in assignment (expression has type "SlugRelatedField[<nothing>]", variable has type "str") [assignment]

I’m reasonably unfamiliar with typing, so trying to decipher what <nothing> meant took me forever as its not documented currently. My understanding is that somewhere in trying to decipher the type for SlugRelatedField mypy believes some code is undefined and so exits early. I believe this to be a problem with this library rather than my implementation, but I am more than happy to provide additional details!

Libraries

name = “djangorestframework”, version = “3.12.4” name = “djangorestframework-stubs”, version = “1.4.0” name = “django”, version = “2.2.24” Python 3.9.7

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:1
  • Comments:5 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
intgrcommented, Nov 3, 2021

Here’s a testable example exhibiting the behavior:

from rest_framework import serializers
from django.contrib.auth.models import User, Group

class TestSerializer(serializers.ModelSerializer):
    username = serializers.CharField(max_length=150)
    group_ids = serializers.PrimaryKeyRelatedField(many=True, source="groups", read_only=True)
    group_names = serializers.SlugRelatedField(many=True, slug_field="name", source="groups", read_only=True)

    class Meta:
        model = User
        fields = ["username", "group_ids", "group_names"]

Output:

main:6: error: Need type annotation for 'group_ids'
main:7: error: Need type annotation for 'group_names'

What I don’t understand is, why is it complaining about the group_ids, group_names fields but not username?

Anyway, one way to shut it up is just annotate it as field type:

from rest_framework.fields import Field
...
    group_ids: Field = serializers.PrimaryKeyRelatedField(many=True, source="groups", read_only=True)

or if you need a more precise type, you can quote it and hint the type vars too:

    group_ids: "PrimaryKeyRelatedField[Group, ...]" = PrimaryKeyRelatedField(many=True, source="groups", read_only=True)
0reactions
sobolevncommented, Jan 21, 2022

This totally can be improved.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Django Rest Framework slug_field error - Stack Overflow
My guess is DRF does not allow nested attribute lookups on SlugRelatedFields. Simple workaround would be to add a username property on the ......
Read more >
Tips and Tricks | TestDriven.io
DRF tip: To represent the target of the relationship with one of its fields, you can use SlugRelatedField in the serializer.
Read more >
Django Rest Framework – An Introduction - Real Python
We have a few options: Be really RESTFUL and make another call to get the user info, which is not good for performance....
Read more >
PyTest with Django REST Framework: From Zero to Hero
Have comprehensive enough tests to isolate what breaks in the piece of code ... developer-tested app knowing the following 4 types of tests:....
Read more >
Typechecking Django and DRF - sobolevn.me
We now have everything installed and configured. Let's type check things! Typechecking views. Let's start with typing views as it is the easiest ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found