E
E
epolyak2016-05-05 16:17:50
Django
epolyak, 2016-05-05 16:17:50

Django-restf-framework, what is the correct HTTP POST method to add data to a model with a ForeignKey?

I started to study djangorestframework - I need to write an API for the site. The official tutorial is simple and quickly passed, then closer to reality I created two simple connected (one-to-many) models:

class ModelA(models.Model):
     ...

class ModelB(models.Model):
    modela = models.ForeignKey(ModelA)
    ...

Serializers for them are simple, as in the tutorial:
class ModelASerializater(serializaters.HyperLinkModelSerialzater):
     class Meta:
            model = ModelA
            fields = (...)

class ModelBSerializater(serializaters.HyperLinkModelSerialzater):
     class Meta:
            model = ModelB
            fields = (...)

The REST api for ModelA works well (who would doubt it), but for ModelB everything is much worse - it cannot be created, it can only be read. The problem is that there is no way to pass ModelA, and there is also no way to pass modela_id.
More precisely, there is a possibility, but he will ignore this field, since he does not serialize it and does not allow it to be serialized forcibly (swears not with good words). I re-read all the off-line documentation on Serializers, ViewSets and other things, tested for two days, debugged, overridden various methods of Serializers, ViewSets, looked at the project code, but did not find information on how to do this (((
Share your experience who has already encountered this problem - what Is there a solution or is there no solution?
you will have to create an intermediate flat model, and then convert it to a normal view. Or is it just Flask? But I already have a working django project and I would like to do everything on one stack.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
un1t, 2016-05-05
@epolyak

Try using serializaters.ModelSerialzater

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question