Reputation: 401
I have two basic classes and i have a serializer like this:
class SomeSerializer(serializers.ModelSerializer):
def get_fields(self, *args, **kwargs):
fields = super(SomeSelializer, self).get_fields()
user = self.context['view'].request.user
fields['project'].queryset = fields['project'].queryset.filter(user=user)
return fields
class Meta:
model = SomeModel
fields = ('id', 'name', 'project', 'user')
read_only_fields = ('id','user')
Project field is a foreign key to model project. How can I get some field from project instead its id?
When I'm trying this:
project = ProjectSerializer(source="project")
I get AttributeError: 'ProjectSerializer' object has no attribute 'queryset'
Upvotes: 1
Views: 841
Reputation: 10609
I will recommend to define a custom attribute using SerializerMethodField
:
class SomeSerializer(ModelSerializer):
project_some_field = SerializerMethodField()
# ...
def get_project_some_field(self, obj):
return obj.some_field
NB: by convention if the attribute name is x
, the the method should be get_x
For more info check here.
Upvotes: 0
Reputation: 1234
You can't Access the Project field using the serializer. First in the python shell create the model's object and then serialize it using
serializer=ProjectSerializer(object)
You can then Access the Project field using -
serializer.data.project
Upvotes: 0