Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework how to save a model with Related Field based on ID

I'm kind of new to DRF. I have Record model that looks like this:

class Records(models.Model):
    owner = models.ForeignKey(User, null=True)
    activity = models.ForeignKey(Activity, null=True)
    time_start = models.DateTimeField(null=True)
    time_end = models.DateTimeField(null=True)

  ...

The RecordSerializer is this one:

class RecordSerializer(serializers.ModelSerializer):

    now = datetime.today()
    owner = serializers.Field(source='owner.username')
    time_start = serializers.DateTimeField(source='now')

    class Meta:
        model = Records
        fields = ("owner", "activity", "time_start")

And this is the view:

class StartApiView(generics.CreateAPIView):
    model = Records
    serializer_class = RecordSerializer

    def pre_save(self, obj):
        obj.owner = self.request.user

The POST request is sent from Backbone and it includes a field with the activity id, for example "{activity:12}". What should I do if I want the view to save the Record and set the activity to the Activity with the id of 12?

like image 558
Alejandro Veintimilla Avatar asked Nov 19 '14 23:11

Alejandro Veintimilla


People also ask

What is the use of REST framework in Django?

Django REST Framework is used to create web APIs very easily and efficiently. This is a wrapper around over the Django Framework. There are three stages before creating an API through REST framework, Converting a Model’s data to JSON/XML format (Serialization), Rendering this data to the view, Creating a URL for mapping to the viewset.

How to pass extra data to a Django REST framework serializer?

In this post, you will learn how to Pass Extra Data to a Django REST Framework Serializer and Save it to the Database. In a standard Django form, a code snippet of the procedure would look like this: form = VoterForm (request.POST) if form.is_valid (): voter = form.save (commit=False) voter.user = request.user voter.save ()

Can a child class override a model field in Django?

In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this isn’t usually permitted for model fields.

Can I use commoninfo model as a base class in Django?

Instead, when it is used as a base class for other models, its fields will be added to those of the child class. The Student model will have three fields: name, age and home_group. The CommonInfo model cannot be used as a normal Django model, since it is an abstract base class.


1 Answers

The accepted answer was true for DRF v2.x but is no longer for newer (3.x) versions, as it would raise this AssertionError:

AssertionError: Relational field must provide a queryset argument, or set read_only=True.

For newer versions, just add the queryset argument to it:

class RecordSerializer(serializers.ModelSerializer):
    activity = serializers.PrimaryKeyRelatedField(queryset=Activity.objects.all())
    // [...] 
like image 131
mathielo Avatar answered Oct 21 '22 19:10

mathielo