I've recently converted my views to generic class-based views, however I've just noticed that POST requests fail on classes that have foreign-keys. The following is my code, followed by the error message.
models.py
class Category(models.Model):
name = models.CharField(max_length=25, blank=False)
class Meta:
ordering = ('id',)
class Task(models.Model):
name = models.CharField(max_length=25, blank=False)
cat = models.ForeignKey(Category, on_delete=models.CASCADE)
class Meta:
ordering = ('id',)
serializers.py
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ('id', 'name', 'cat_id')
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('id', 'name')
views.py
class TaskList(generics.ListCreateAPIView):
"""
List all Tasks (OR for specified cat_id)
"""
queryset = Task.objects.all()
serializer_class = TaskSerializer
filter_fields = ('cat_id',)
urls.py
path('tasks/', views.TaskList.as_view()),
Error returned
django.db.utils.IntegrityError: null value in column "cat_id" violates not-null constraint
DETAIL: Failing row contains (51, buy-some, null).
REQUEST content: JSON Object
{
"name": "buy-some",
"cat_id": 1
}
Additionally, Content-Type, Accept headers are set to application/json .
Category with id=1 exists
Probably what you want is to define the field cat
in your TaskSerializer
to be a PrimaryKeyRelatedField
(documentation here) , in your case would be:
class TaskSerializer(serializers.ModelSerializer):
cat = PrimaryKeyRelatedField(queryset=Category.objects.all())
class Meta:
model = Task
fields = ('id', 'name', 'cat')
Then in your request just send the pk in the "cat"
field like so:
{
"name": "buy-some",
"cat": 1
}
This should do the trick.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.