Banks
Banks

Reputation: 175

Nested Relationship in Django Doesn't Work

These are my models here:

class Site(models.Model):
    siteID = models.CharField(max_length=255, primary_key=True)

class EndDevice(models.Model):
    class Meta:
        unique_together = ("edevID", "siteID")

    edevID = models.CharField(max_length=255) 
    siteID = models.ForeignKey(Site, related_name='endDeviceList', on_delete=models.CASCADE)
    deviceCategory = models.BigIntegerField()

This is my serilaizer:

class DeviceSerializer(serializers.ModelSerializer):
    class Meta:
        model = EndDevice
        fields = ("edevID", "siteID", "deviceCategory")
class SiteSerializer(serializers.ModelSerializer):
    endDeviceList = DeviceSerializer(many = True, read_only=True)

    class Meta:
        model = Site
        fields = ("siteID", "endDeviceList")

This is my view:

class IndividualSite(generics.RetrieveUpdateDestroyAPIView):
    '''
    PUT site/{siteID}/
    GET site/{siteID}/
    DELETE site/{siteID}/
    '''
    queryset = EndDevice.objects.all()
    serializer_class = SiteSerializer

I am trying to get/put/delete results using this class and I am trying to get all the EndDevice instances which have same siteID. But my serialzer only shows the siteID and doesn't show the endDeviceList (which should have the instants of the model EndDevice)

The problem is quite similar to this link:django rest-farmework nested relationships.

I have been trying different ways to serialize the objects, I think this is probably the smartest way, but have been really unsucccessful. Any help will be appreciated. The urls.py: urlpatterns = [

urlpatterns = [path('site/<str:pk>/', IndividualSite.as_view(), name = "get-site"),]

And it is connected to the main urls.

Upvotes: 0

Views: 75

Answers (1)

Exprator
Exprator

Reputation: 27503

you are using read_only field for the Foreign relationship, remove that, as read_only wont display them

class SiteSerializer(serializers.ModelSerializer):
    endDeviceList = DeviceSerializer(many = True)

Upvotes: 1

Related Questions