Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NestedHyperlinkedIdentityField add parameter null for return None if attribute not found in object #174

Open
aztecrabbit opened this issue Jun 1, 2020 · 1 comment

Comments

@aztecrabbit
Copy link

Model

class Person(models.Model):
    child = models.ForeignKey('Person', on_delete=models.SET_NULL, null=True)

Serializer

class PersonSerializer(NestedHyperlinkedModelSerializer):
    child = NestedHyperlinkedIdentityField(
        view_name='person-detail',
        parent_lookup_kwargs={
            'pk': 'child__pk',
        },
    )

    class Meta:
        model = Person
        fields = '__all__'

I want child is None if child object is None, instead of raise AttributeError: 'NoneType' object has no attribute 'pk'

@gongul
Copy link

gongul commented Jan 27, 2021

There is no problem when tested as below. Give me more information.

serializer

class AddressSerializer(NestedHyperlinkedModelSerializer):
    user = NestedHyperlinkedIdentityField(
        view_name='user-detail',
        parent_lookup_kwargs={
            'user_pk': 'user__pk',
        },
    )
    class Meta:
        model = Address
        fields = '__all__'

model

class Address(models.Model):
    id = models.BigAutoField(primary_key=True)
    user = models.ForeignKey(
        User, on_delete=models.SET_NULL, related_name='addresses', null=True)

view

class AddressViewSet(viewsets.ModelViewSet):
    serializer_class = AddressSerializer

    def get_queryset(self):
        return Address.objects.filter(user=self.kwargs['user_pk'])

url

domains_router = routers.NestedSimpleRouter(router, r'users', lookup='user', trailing_slash=False)
domains_router.register(r'addresses', AddressViewSet, basename='user-address')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants