4

In my django app:

models.py:

class Destination(models.Model):
    name=models.CharField(max_length=30)

class Ride(models.Model):
    driver = models.ForeignKey('auth.User', related_name='rides_as_driver')
    destination=models.ForeignKey(Destination, related_name='rides_as_final_destination')
    leaving_time=models.TimeField()
    num_of_spots=models.IntegerField()
    passengers=models.ManyToManyField('auth.User', related_name="rides_as_passenger")
    mid_destinations=models.ManyToManyField(Destination, related_name='rides_as_middle_destination')

serializer:

class RideSerializer(serializers.ModelSerializer):
    driver = serializers.ReadOnlyField(source='driver.username')

    class Meta:
        model = Ride
        fields = ('id', 'driver', 'destination', 'leaving_time',
                  'num_of_spots', 'passengers', 'mid_destinations')
        read_only_fields = ('id', 'driver', 'passengers', 'mid_destinations')

As you can see, mid_destinations is a ManyToMany field.

My question is- how do I POST to a ManyToMany field?

to the regular fields I can just POST with a json like this, from my android app:

{ "destination" : "LA", "num_of_spots" : "3", "leaving_time" : "14:35"} etc.

how do I POST to the ManyToMany field?

Thanks ahead!

tamakisquare
  • 16,659
  • 26
  • 88
  • 129
Ofek Agmon
  • 5,040
  • 14
  • 57
  • 101

2 Answers2

0

You should take two steps:

  1. Remove 'mid_destinations' from the list of read_only_fields

  2. Send POST data like {"mid_destinations": ["LA", "SF", "SD"], ...}

I am assuming that you are using DRF 3.

Mehdi
  • 1,260
  • 2
  • 16
  • 36
tamakisquare
  • 16,659
  • 26
  • 88
  • 129
  • thanks for your answer. the reason "mid_destination" is a read_only field is - I don't want the user to HAVE to put the mid_destination field, meaning - The user should be able to create a Ride WITHOUT having mid_destinations field, and WITH having a mid_destination field. can I just send an empty array when the User doesn't have a value for it? – Ofek Agmon Jul 08 '15 at 05:16
  • @OfekAgmon - Yes, empty array is exactly what the client-end should send when user doesn't provide any mid_destination. – tamakisquare Jul 08 '15 at 17:03
  • @tamakisquare - I think data shoud be like { "destination" : "LA", "num_of_spots" : "3", "leaving_time" : "14:35", "mid_destinations": ["SF", "SD"], ...} – Rajesh Kaushik Jul 12 '15 at 09:33
  • @RajeshKaushik - You're right! I carelessly put down *"destination"* when I meant to say *"mid_destinations"*. Thanks for pointing that out. I hope I didn't confuse the OP. – tamakisquare Jul 12 '15 at 22:46
0

You should send a list of strings that contains a pk of many2many field

For example following array cause error

destination = [1, 2, 3]

but list blow not

destination = ["1", "2", "3"]
Bambier
  • 586
  • 10
  • 16