0

I am relatively new to DRF and having hard time updating the foreign key in my model via POST request.

    # Model for Event.

        class Event(models.Model):
              heading = models.TextField()
              event_construction_site = models.ForeignKey(
                  ConstructionSite, on_delete=models.CASCADE, related_name='construction_site_events', null=True)
            
              def __str__(self):
                  return str(self.id)
    
    
        class ConstructionSiteShortSerializer(serializers.ModelSerializer):
            class Meta:
                model = ConstructionSite
                fields = ['id']
    
     # Serializer for Event.

        class EventSerializer(serializers.ModelSerializer):
            event_construction_site = ConstructionSiteShortSerializer()
            event_posted_by = CustomUserSerializer()
        
            class Meta:
                model = Event
                fields = ('id', 'heading', 'event_construction_site')

Structure of my GET response is as follows:

  {
    id: 1,
    heading: "Truck with formwork arrived",
    event_construction_site: {
      id: 3
    }
  }

My concern here is how can I update the id of event_construction_site?

I tried updating it like as follows:

{
    "heading": "a",
    "event_construction_site": {"id": 2}
}

Dute to id of event_construction_site being nested field I get an error that says =>

The `.create()` method does not support writable nested fields by default.
6
  • Does this answer your question? The `.create()` method does not support writable nested fields by default. Commented Dec 19, 2020 at 19:03
  • 1
    I looked into it @DušanMaďar but had a thought that whether just to updated an ID field do we need to do method overiding? or is there any other way we can achieve the same, in my case if updating an id requires me to overide create & to_representation method then it doesn't make much sense as I have to do this in almost all of my views as I have nested data present in all of them. Commented Dec 19, 2020 at 19:08
  • 1
    Why do you not use a PrimaryKeyRelatedField instead of your event_construction_site serializer. I believe this will solve your problem. Commented Dec 19, 2020 at 19:20
  • @BriseBallochesgood suggestion that won't solve becuase if I use it I gest this err => AssertionError: Relational field must provide a queryset argument, override get_queryset, or set read_only=True , and if I set read_only=True to true then event_construction_site won't appear in my POST payload. Commented Dec 19, 2020 at 19:22
  • 1
    Just add the argument queryset=ConstructionSite.objects.all() to PrimaryKeyRelatedField. Commented Dec 19, 2020 at 19:24

1 Answer 1

2

You can use a PrimaryKeyRelatedField.

class EventSerializer(serializers.ModelSerializer):
            event_construction_site = serializers.PrimaryKeyRelatedField(queryset=ConstructionSite.objects.all())
            event_posted_by = CustomUserSerializer()
        
            class Meta:
                model = Event
                fields = ('id', 'heading', 'event_construction_site')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.