I'm trying to expose an API to my Django model through Django REST framework.
I have an object Observation
. An observation can contain multiple things that have been observed. So I represented it like this:
class Observation(models.Model):
photo_file = models.ImageField( upload_to=img_dir, blank=True, null=True )
titestamp = models.DateTimeField(blank=True, null=True)
latitude = models.FloatField()
longitude = models.FloatField()
class ObservedThing(models.Model):
thing = models.ForeignKey(Thing) # the thing being observed
observation = models.ForeignKey(Observation, related_name='observed_thing')
value = models.FloatField()
As I understand this is a one-to-many relationship.
I now have an API View:
class ObsvList(generics.ListCreateAPIView):
"""
API endpoint that represents a list of observations.
"""
model = Observation
serializer_class = ObsvSerializer
and the corresponding serialiser:
class ObsvSerializer(serializers.ModelSerializer):
observed_thing = serializers.PrimaryKeyRelatedField(many=True)
class Meta:
model = Observation
What do I have to do to be able to POST an observation with several things detected? I cannot figure it out. Many thanks.
(answer more or less copied from another similar but less clear question)
To create multiple related objects in a single POST requires writable nested serializers which are not yet available.
Full support is a work in progress, but in the mean time one (hacky) solution is to override the
create
method in the view in each case:Probably not ideal, but it works for me until the proper way comes along.
The other option is to create the related
Observation
objects individually with separate POSTs, and the use PrimaryKeyRelatedField or HyperlinkedRelatedField to make the associations in the finalObservedThing
POST.I know this thread has already an answer but I started working to solve this problem, and since this post was one of my inspirations, I would like to share my final solution. It can be useful to someone. I have the models, so the parent class:
then, the child class:
I had to define the serializers, since I didn't want to create a router accessible url to directly manage Children objects, but I wanted to create them through the ModelViewSet of the parent ModelViewSet, this is what I needed:
I was then ready to create the ModelViewSet, overriding/extending the create/update mixins, and make it generic in order to reuse it for other cases:
So I can reuse it for every nested relationship case I have in my app like this:
And in the end, the routing:
It works like a charm!
you need to use many to many relationship for creating a temporary table that will store the keys and associate data automatically.