Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two different models in Django Rest Framework

I have two unrelated models:

class ModelOne(models.Model):
    fieldA = models.CharField(max_length=50)
    fieldB = models.CharField(max_length=50)

class ModelTwo(models.Model):
    fieldC = models.CharField(max_length=50)
    fieldD = models.CharField(max_length=50)

I want to build one serilaizer with DRF so that I can have a returned json like this one:

},...
{ 'fieldA' : 'a',
  'fieldB' : 'b',
  'fieldC' : 'c',
  'fieldD' : 'd'
}, ...

I'm unable to do it right now. I've tried this module but I run into an error.

like image 802
iMitwe Avatar asked Aug 25 '16 10:08

iMitwe


Video Answer


1 Answers

Something like this:

from rest_framework.serializers import ModelSerializer

class ModelOneSerializer(ModelSerializer):
    """
    A serializer for ``ModelOne``.
    """
    class Meta(object):
        model = ModelOne


class ModelTwoSerializer(ModelSerializer):
    """
    A serializer for ``ModelTwo``.
    """
    user = ModelOneSerializer()

    class Meta(object):
        model = ModelTwo
like image 58
Marin Avatar answered Sep 27 '22 21:09

Marin