I am trying to get a list of templates from a Django model, but I always get an error. Below is the error whenever I attempt to retrieve the list of job templates. I get this error because it doesn't recognise the field template_name.
AttributeError: Got AttributeError when attempting to get a value for field
template_name
on serializerListJobTemplateSerializer
. | The serializer field might be named incorrectly and not match any attribute or key on theJob
instance. | Original exception text was: 'Job' object has no attribute 'template_name'.
Job Model:
class Job (Dates, ID):
name = models.CharField(max_length=255, validators=[name_validation])
is_remote = models.BooleanField(default=False)
company = models.ForeignKey(to="companies.company", related_name="%(class)s", on_delete=models.CASCADE)
Template Model:
class JobTemplate(Dates, ID):
template_name = models.CharField(max_length=255)
jobs = models.ForeignKey(to="jobs.Job", related_name="%(class)s", on_delete=models.CASCADE)
objects = BulkUpdateOrCreateQuerySet.as_manager()
class Meta:
db_table = 'job_template'
def __str__(self):
return name
class ListJobTemplateSerializer(serializers.ModelSerializer):
"""List all templates of a job."""
job_title = serializers.CharField(source="name")
class Meta:
model = JobTemplate
fields = ["id", "job_title", "template_name"]
CodePudding user response:
The problem with your code is that you must be making some mistakes in your views. There's no problem with your model and with your serializer, there are fine. As there's not enough information provided the possible problem lies in the queryset, as your queryset is fetching Job object, not JobTemplate object you have to revamp your queryset for fetching JobTemplate.
Reference Document that can help you with queryset: https://docs.djangoproject.com/en/3.2/ref/models/querysets/