0

So I have a model like this

class DataSheet(BaseModel):
    """
    Represents a single dataSheet.
    dataSheets have their own model at the core. Model data is added to
    the dataSheets in the form of separate records.
    """

    class Meta:
        verbose_name = 'datasheet'
        verbose_name_plural = 'datasheets'
        ordering = ['position', 'cluster']
        required_db_features = {
            'supports_deferrable_unique_constraints',
        }
        constraints = [
            models.UniqueConstraint(
                fields=['position', 'cluster'],
                name='deferrable_unique_datasheet_position',
                deferrable=models.Deferrable.DEFERRED
            )
        ]

    def __str__(self):
        return self.name

    objects = managers.DataSheetsManager()
    positions = managers.PositionalManager()
    position = models.PositiveSmallIntegerField(db_index=True, editable=True)
    name = models.CharField(max_length=100, validators=[MinLengthValidator(2)], db_index=True)
    description = models.CharField(max_length=1024, null=True, blank=True, db_index=True)
    owner = models.ForeignKey('api_backend.Member', on_delete=models.CASCADE, db_index=True, editable=False)
    fields = models.ManyToManyField('api_backend.Field')
    overwrites = models.ManyToManyField('api_backend.RoleOverwrite')
    parent = models.ForeignKey('api_backend.Category', on_delete=models.CASCADE, null=True, blank=True)
    cluster = models.ForeignKey('api_backend.Cluster', on_delete=models.CASCADE, editable=False)

    REQUIRED_FIELDS = [name, owner, cluster]

and a serializer like this

class DataSheetSerializer(serializers.ModelSerializer):
    """
    A serialized DataSheet Object.
    Datasheets have their own:
        - array of fields
        - array of role-overwrites
    """

    def get_fields(self):
        fields = super(DataSheetSerializer, self).get_fields()
        fields['parent'].queryset = self.cluster.categories.all()

        return fields

    class Meta:
        model = DataSheet
        read_only_fields = ['position']
        fields = '__all__'

    # need to make sure that the parent category of the datasheet
    # belongs to the datasheet's cluster only.

    fields = partial.PartialFieldSerializer(many=True, read_only=True)
    overwrites = partial.PartialOverWriteSerializer(many=True, read_only=True)

the thing is, I want to access the serializer model's cluster field inside of the get_fields method. However, I couldn't do the same. Can someone help me?

I've seen other answers involving initial_data, but that doesn't work here.

fields['parent'].queryset = self.cluster.categories.all()

cluster is an unresolved reference here.

1 Answer 1

1

self in get_fields is DataSheetSerializer instance not DataSheet model instance. hence it should not have cluster property. you can not access model DataSheet instance in get_fields as it gets fields from class DataSheet not from its instance. you can validate the field like

class DataSheetSerializer(serializers.ModelSerializer):
    # ... other code

    def validate(self, data):
         parent = data.get('parent')
         # check if parent is valid i.e in queryset
         # if yes return data
         # else raise serializers.validationError
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.