Ad

'JobSerializer' Object Has No Attribute 'email' What I Am Missing?

- 1 answer

serializers.py

class JobSerializer(serializers.ModelSerializer):
    # image = Base64ImageField(max_length=None, 
    #                         use_url=True)
    # applicant = serializers.ForeignKe
    applicant = serializers.StringRelatedField(many=True)
    email = serializers.SerializerMethodField("get_username_from_user")
    company_name = serializers.SerializerMethodField("get_company_name_from_user")
    class Meta:
        model = Jobs
        fields = ['company_name', 'email',  'title', 'desc', 'image', 'price',  'category', 'applicant']
        # extra_kwargs = {"email": {"required": False}}




    def get_username_from_user(self, jobs):
        email = jobs.user.email
        return email

    def get_company_name_from_user(self, jobs):
        company_name = jobs.user.company_name
        return company_name

views.py

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def api_detail_jobs_view(request, id):
    try:
        jobs = Jobs.objects.get(id=id)
    except Jobs.DoesNotExist:
        data = {}
        data['response'] = "Job does not exist"
        return Response(data, status=status.HTTP_404_NOT_FOUND)

    
    if request.method == "GET":

        serializer = JobSerializer(jobs)
        user = request.user
        if user == serializer.email:
            data = {}
            auth_show = serializer
            data['title'] = auth_show.title 
            data['applicant'] = auth_show.applicant
            return Response(data)
        else:
            no_auth_show = serializer
            data = {}
            data['title'] = no_auth_show.title
            return Response(data)

here is serializers.py in which 'email' is included. i know i am missing something very clear but it took hours to realise :) so any help will be appriciated i am trying to show 'applicants' only to users who owns the 'job' but i can't pass 'email' from serializer in to the view. I can't pass any attribute from serializer in to data dict.

Ad

Answer

As shown in the documentation of DRF, after serializing an object you can access its fields via the data attribute. So it would look like serializer.data['email'].

And one extra tip, consider using the Django shortcut get_object_or_404() instead of that try/except block. Good luck!

Ad
source: stackoverflow.com
Ad