Alexander Teut
2018-05-29 15:13:11 UTC
0down votefavorite
<https://stackoverflow.com/questions/50587735/losing-foreign-key-value-in-django-rest-serializer#>
I've simplified my code to make problem more clear.
I have two related models in my Django REST project. In my models.py:
class Project(Models.model):
name = models.CharField(max_length=150)
class Item(models.Model):
project = models.ForeignKey(Project, blank=True, on_delete=models.CASCADE)
data = models.TextField(blank=True, null=True)
Then I create a serialiser:
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('id', 'project_id', "data")
View set:
class ItemViewSet(viewsets.ModelViewSet):
queryset = Item.objects.all()
serializer_class = ItemSerializer
filter_backends = (DjangoFilterBackend,)
filter_fields = ('project_id')
Router:
router.register(r'items', ItemViewSet)
This implementation works fine for models without foreign keys. But when I
post something like:
{
project_id: 1,
data: "text"
}
(the project with id=1 exists)
my ItemSerializer gets just { data: "text" } to validated_fields.
The project_id field is *completely lost* during validation.
How to configure Serializer or ViewSet to make it workable?
<https://stackoverflow.com/questions/50587735/losing-foreign-key-value-in-django-rest-serializer#>
I've simplified my code to make problem more clear.
I have two related models in my Django REST project. In my models.py:
class Project(Models.model):
name = models.CharField(max_length=150)
class Item(models.Model):
project = models.ForeignKey(Project, blank=True, on_delete=models.CASCADE)
data = models.TextField(blank=True, null=True)
Then I create a serialiser:
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ('id', 'project_id', "data")
View set:
class ItemViewSet(viewsets.ModelViewSet):
queryset = Item.objects.all()
serializer_class = ItemSerializer
filter_backends = (DjangoFilterBackend,)
filter_fields = ('project_id')
Router:
router.register(r'items', ItemViewSet)
This implementation works fine for models without foreign keys. But when I
post something like:
{
project_id: 1,
data: "text"
}
(the project with id=1 exists)
my ItemSerializer gets just { data: "text" } to validated_fields.
The project_id field is *completely lost* during validation.
How to configure Serializer or ViewSet to make it workable?
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-framework+***@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.