OVHcloud Community

Welcome to your community space. Ask questions, search for information, post content, and interact with other OVHcloud Community members.

Django rest framework save parent records on same model


I have model like this:

class Company(models.Model):
""“Company model”""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
active = models.BooleanField(default=False, blank=True, null=True)
type = models.JSONField(max_length=200, blank=True, null=True)
name = models.CharField(max_length=200, blank=True, null=True)
alias = models.CharField(max_length=200, blank=True, null=True)
telecom = models.JSONField(max_length=200, blank=True, null=True)
address = models.CharField(max_length=200, blank=True, null=True)
part_of = models.ForeignKey(“company.Company”, on_delete=models.SET_NULL, null=True,
blank=True, related_name=“parent”)
created_at = models.DateTimeField(auto_now_add=True, blank=False, null=True)
updated_at = models.DateTimeField(auto_now_add=True, blank=False, null=True)
deleted_at = models.DateTimeField(default=None, blank=True, null=True)

class Meta:
db_table = ‘organizations’

def str(self):
And serializer:

class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = 'all
read_only_fields = (“id”,)
part_of = serializers.PrimaryKeyRelatedField(queryset=Company.objects.all())

def create(self, validated_data):

part_of = validated_data.pop("part_of")

if part_of:
    company_id = Company.objects.create(**part_of)
    validated_data['part_of'] = company_id

company = Company.objects.create(**validated_data)
return company

And view:

class CompanyViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin):
serializer_class = serializers.CompanySerializer
queryset = Company.objects.all()

def get_queryset(self):
    return self.queryset.all()

def perform_create(self, serializer):

It is working fine with empty value of “part_of”:"", but doesn’t work while I pass value for part_of. part_of is basically a parent company which I am trying to create. so my expectation is create a company(part_of) first, get it’s id and make that id as foreign key for another company. Anyone implemented similar to this? Or what I am doing wrong here, suggestions, help is appreciated. Thanks in advance.

The error I am getting is:

“part_of”: [
"“{ ‘name’: ‘Parent of Organization’, ‘telecom’: [{‘system’: ‘phone’, ‘value’: ‘677-7777’}, {‘system’: ‘email’, ‘value’: ‘’}], ‘address’: [{‘line’: [‘3300 Washtenaw Avenue, Suite 227’], ‘city’: ‘Amherst’, ‘state’: ‘MA’, ‘postalCode’: ‘01002’, ‘country’: ‘USA’}]}” is not a valid UUID."