Home > Software engineering >  How to post the model with foreign key?
How to post the model with foreign key?

Time:03-07

I have a model like this

one has a foreign key of the other.

class MyCategory(models.Model):
    name = models.CharField(max_length=30)
    description = models.TextField(verbose_name='description')

class MyItem(models.Model):
    file = models.FileField(upload_to='uploaded/')
    category = models.ForeignKey(MyCategory, on_delete=models.CASCADE)
    @property
    def category_name(self):
        return self.category.name

class MyItemViewSet(viewsets.ModelViewSet):
    queryset = MyItem.objects.all()
    serializer_class = MyItemSerializer

class MyCategoryViewSet(viewsets.ModelViewSet):
    queryset = MyCategory.objects.all()
    serializer_class = MyCategorySerializer

Now I want to upload the file to MyItem and set the category at the same time.

At first, I try this. ( I have one category of data which has id = 1)

curl -X POST -F [email protected] -F 'category=1' http://localhost/items/

it shows Exception Value: (1048, my_category_id cannot be null)

category=1 dosen't accepted as foreign key.

So, is it possible to use the curl command to set the ForeignKey?

Solution

I added the category_id in fields of serializer

class MyItemSerializer(serializers.Serializer):
    file = serializers.FileField()
    category_name = serializers.ReadOnlyField()
    category_id = serializers.IntegerField() # add here.
    class Meta:
        model = Donation
        fields = [
            'file',
            'category_id', # add here
            'created_at',
        ]

CodePudding user response:

You set category=1 so Django expects to send a category object but if you need to send the id of the object, set category_id=1

curl -X POST -F [email protected] -F 'category_id=1' http://localhost/items/
  • Related