class Bar1(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
data = models.CharField(max_length=20)
class Bar2(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
data = models.IntegerField()
class Foo(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT)
object_id = models.UUIDField()
contentObject = GenericForeignKey()
class FooViewSet(viewsets.ModelViewSet):
serializer_class = FooSerializer
queryset = Foo.objects.all()
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
fields = ('__all__')
{
"content_type": "<<uuid>>",
"object_id" : "<<uuid>>
}def create(self, validated_data): content_type = validated_data.get("object_id") taggedObject = Bar1.objects.get(id=content_type) if Bar1.objects.filter(id=content_type).count() > 0 else None taggedObject = Bar2.objects.get(id=content_type) if Bar2.objects.filter(id=content_type).count() > 0 and taggedObject == None else None
if taggedObject is not None: contentType = ContentType.objects.get_for_model(taggedObject) if contentType is not None: validated_data["content_type"] = contentType validated_data["object_id"] = taggedObject return super(FooSerializer, self).create(validated_data)
class Meta: model = Foo fields = ('__all__') extra_kwargs = { 'content_type': {'required': False}, }So apparently I just miss assigned the validated_data["object_id"]. It should be assigned with an id not the instance. After I updated the create serializer method to:
def create(self, validated_data):
content_type = validated_data.get("object_id")
taggedObject = Bar1.objects.get(id=content_type) if Bar1.objects.filter(id=content_type).count() > 0 else None
taggedObject = Bar2.objects.get(id=content_type) if Bar2.objects.filter(id=content_type).count() > 0 and taggedObject == None else None
if taggedObject is not None:
contentType = ContentType.objects.get_for_model(taggedObject)
if contentType is not None:
validated_data["content_type"] = contentType
validated_data["object_id"] = taggedObject.id
return super(FooSerializer, self).create(validated_data)