Search code examples
django-rest-frameworkforeign-keysdjango-serializergeneric-foreign-key

Saving(create,update) along with foreignkey value from another model which is related user model


It may be a challenging question if you didn't get rightly. Here I have three models in which department model should be created by taking its place name from Place model which is related to the staff model. The Staff Model is in a OneToOneField relationship with User, so when a user creates a department the place name should be passed like HiddenField in HTML . This place name is related to place model with the user with GenericForeignKey. i have created a serializer which is not working as expected, it is returning the place name , .

In shortly I want to create a department while place should be selected from current user ID

  class Staff(BaseModel):
        ROLES = [
            ('ADMIN', 'Admin'),
            ('TEACHER', 'Teacher')
        ]
        auth_user = models.OneToOneField(User, on_delete=models.CASCADE)
        name = models.CharField(max_length=50)
        school_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
        school_id = models.PositiveIntegerField()
        school = GenericForeignKey('school_content_type', 'school_id')
        role = models.CharField(null=True, blank=True, choices=ROLES, max_length=20)

class Places(BaseModel):
    name = models.CharField(max_length=50)
    code = models.CharField(max_length=12, unique=True)



class Department(BaseModel):
    TYPES = [
        ('ONLINE', 'Online'),
        ('OFFLINE', 'OfFline')
    ]
    department_type = models.CharField(max_length=15, choices=TYPES)
    service_no = models.CharField(max_length=50)
    instructions = models.TextField(null=True, blank=True)
    place = models.ForeignKey(Places, to_field='code', db_column='place_code', on_delete=models.PROTECT)

SERIALIZERS

class DepartmentCreateSerializer(serializers.ModelSerializer):
    place_code=serializers.CharField(read_only=True)
    class Meta:
        model=Department
        fields = ('department_type','service_no','instructions')
    def get_place(self, request):
            user_id=self.context['request'].user.id
            school_id=Staff.objects.get(auth_user_id= user_id).school_id
            places_code_name=Places.objects.get(id= school_id).name 

Solution

  • class PlacesSerializer(serializers.ModelSerializer):
        class Meta:
            model = Places
            fields = ('id', 'code', 'name')
    
    
    from places.serializers import PlacesSerializer
    class DepartmentCreateSerializer(serializers.ModelSerializer):
            place= PlacesSerializer(read_only=True)
            class Meta:
                model=Department
                fields = ('place','service_no','instructions')
            def validate(self, attrs):
                palce_obj = self.context['request'].user.staff.place()
                attrs.update({'place': place_obj})
                attrs = super().validate(attrs)
                if not attrs.get('place', None):
                    raise serializers.ValidationError({'place': ["Place required"]})
                return attrs