5

I have two models in my models.py. I need to return a json response which includes data from two tables. How should my view and serializer look like?

class Device(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    device_name = models.CharField(max_length=200, null=True, blank=True )
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.device_name)

class StatusActivity(models.Model):
    OFFLINE = 1
    ONLINE = 2
    STATUS = (
        (OFFLINE, ('Offline')),
        (ONLINE, ('Online')),
    )
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    device_id = models.ForeignKey(Device, related_name='StatusActivity', on_delete=models.CASCADE)
    changed_to = models.PositiveSmallIntegerField(choices=STATUS)
    modified_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.device_id)

Expected Response:

 {
    "device_id":"",
    "device_name":"",
    "changed_to":"",
    "modified_at":"",
  }

UPDATE: I set my views.py and serializer.py as below. I am checking

Serializer.py

class DeviceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Device
        fields = '__all__'

class StatusActivitySerializer(serializers.ModelSerializer):

    class Meta:
        model = StatusActivity
        fields = '__all__'

class ListSerializer(serializers.Serializer):
    # devices = DeviceSerializer(many=True)
    # activities = StatusActivitySerializer(many=True)

    class Meta:
        model = [Device, StatusActivity]
        fields = ['device_id', 'device_name', 'changed_to', 'modified_at']

Views.py

class DeviceListView(generics.ListAPIView):
    queryset = Device.objects.all()
    serializer_class = ListSerializer

class StatusActivityListView(generics.ListAPIView):
    queryset = StatusActivity.objects.all()
    serializer_class = StatusActivitySerializer
4
  • What you have tried? Show some effort Commented Nov 30, 2019 at 16:14
  • Why do you have 2 views? If you want one response, you should have only one view. Commented Nov 30, 2019 at 16:49
  • Okey, and how it should look like? I still can not retrieve a data like a describe in my question above. Can you point how can i do that? @dirkgroten Commented Nov 30, 2019 at 16:51
  • First, are you fetching a Device or a StatusActivity (i.e. which pk/id is passed in your url)? Create the serializer for that model, then add the fields from the other model manually by specifying the source. Commented Nov 30, 2019 at 17:10

2 Answers 2

3

Actually you don't need to have two separated views for this, because you can easily serialize relations from one serializer class. Take a look at this useful answer: How do I include related model fields using Django Rest Framework?

For your case you can write something like this:

class StatusActivitySerializer(serializers.ModelSerializer):
    device_name = serializers.CharField(source='device_id.device_name')

    class Meta:
        model = StatusActivity
        fields = ('changed_to', 'modified_at', 'device_id', 'device_name')

Something that worth to note:

  1. it's a good idea for ForeignKey field use device name instead of device_id;
  2. related_name arg should have a name for reverse access. Keep it meaningful, e.g. status_activities is a good choice.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot. It gives me what I need. But I didn't understand your first point. Why should I use device_name instead of device_id? @funnydman
@erondem Ah, actually there is misunderstanding I'm specially highting device and device_id to make the difference. You should use device instead of device_id because Django automatically appends _id postfix, so in your case you'll have device_id_id field and more likely that is not what you want.
0

filter the status activity. you can refer the foreignkey. eg:

items = []
for statusact in StatusActivity.objects.all():
    items.append({
        "device_id":statusact.device_id.id,
        "device_name":statusact.device_id.device_name,
        "changed_to":statusact.changed_to,
        "modified_at":statusact.modified_at,
    })

1 Comment

I have 3 entry in db but it respond me this [ {}, {}, {} ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.