I would like to save an instance of 'Feedback' object on my database, the feedback object have a foreignkey to 'Client', and a genericforeignkey because it can be related to 'Vendor' or 'Store', i made 2 url's that allows POST, one to create feedback for vendor and another to create feedback for store, both receive the primarykey.
Class diagram example:
This is my approach:
@api_view(['POST'])
def store_feedback_view(request, store_id):
serializer = FeedbackSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
The serializer is valid, but while trying to save give me the following error:
NOT NULL constraint failed: feedback_feedback.object_id
NOT NULL constraint failed: feedback_feedback.content_type_id
This happens because the feedback object have the genericforeignkey not NULL:
class Feedback(models.Model):
comment = models.TextField(verbose_name='Comment', max_length=300, blank=True, null=True)
client = models.ForeignKey(Client, verbose_name="Client feedback", related_name="feedbacks")
limit = models.Q(app_label='core', model='store') | models.Q(app_label='core', model='vendor')
content_type = models.ForeignKey(ContentType,
limit_choices_to=limit)
object_id = models.PositiveIntegerField(verbose_name="Related object ID")
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
app_label = 'feedback'
How i can create an object of feedback on POST method?
This is a example of request on feedback/store/(?P<store_id>\d+)/
{
"comment": "Nice store",
"client": 1
}