Tuesday 15 July 2014

python - Include intermediary (through model) in responses in Django Rest Framework -


I have a question about dealing with the M2M / model and their presentation in the Dzegoño rest of the framework. Take a classic example:

models.py:

  import model from class members (models.Model): name = models.CharField (MAX_LENGTH = 20) Groups = models.ManyToManyField ('group', '' membership '') through group group (models.Model): name = models.CharField (MAX_LENGTH = 20) class membership (models.Model): member = models. ForeignKey ('member') group = models.ForeignKey ('group') join_date = models.DateTimeField ()   

serializers.py:

  import. .. Class MemberSerializer: Model Metadata: Class Meta Model = Member Class GroupSerializer (ModelSerializer): Class Meta Model Group =   

views.py:

  Known. .. Class MemberViewSet (ModelViewSet): QuerySet = Member.objects.all () serializer_class = MemberSerializer class GroupViewSet (ModelViewSet): QuerySet = group.objects.all () serializer_class = GroupSerializer   

Members To get an example, I successfully get all the members of the member and also grow up - although I only get the details of the group, without further details which comes from the membership model.

In other words, to get hope :

 ['id': 2, 'name': 'some member', 'group' : [{'Id': 55, 'name': 'group 1' 'United Nations': 34151564}, {'id': 56, 'name': 'group 2' 'join_date': 1120029 9}]   

join_date

I have a lot of solutions, I have tried, which certainly includes and no one wants to give a fairly simple answer about it - what do I want to include these additional areas? should do? I got this straight and straight ahead with Diego-Tastipi, but there were some other problems and the rest of the framework was liked.

On your member serializer, define a field on it:

 < Code> groups = MembershipSerializer (source = 'subscription_set', many = true)   

and then on your membership serializer, you can create:

  class Membership StyleIliser (Serializer: Hyperlinked Model Surger): id = serializers.Field (source = 'group .id') name = serializers.Field (source = 'group.name') class meta: model = membership field = ('id', 'Name', 'penalty', '')   

A random value of this is the overall effect of creating a group, as the source of which is the membership you want, and then uses custom serializer to remove those bits you want to display.

Edit: Commented as @bruthf, serializers.field was renamed to serializers.ReadOnlyField in DRF 3.0, Therefore read this word:

  class MembershipSerializer (serializers.HyperlinkedModelSerializer): id = serializers.ReadOnlyField (source = 'group.id') name = serializers.ReadOnlyField (source = 'group.name ') Class         

No comments:

Post a Comment