简体   繁体   中英

Django Model not recognising model fields using Serialiser Class Generic Views

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 serializer ListJobTemplateSerializer . | The serializer field might be named incorrectly and not match any attribute or key on the Job 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"]

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM