TypeError: Field 'id' expected a number but got <django.db.models.query_utils.query_utils.DeferredAttribute object

TypeError: Field 'id' expected a number but got <django.db.models.query_utils.query_utils.DeferredAttribute object

正在尝试仅针对特定的 NewHireTraining 显示受训者。

我正在将额外的上下文数据传递给 training_details 视图 class 以向受训人员显示与受训人员 class 下的外键相关的受训人员。

它返回属性 id 的位置而不是 id 值。

非常感谢帮助

models.py

class NewHireTraining(models.Model):
    location = models.ForeignKey(Location, on_delete=models.CASCADE)
    program = models.ForeignKey(Program, on_delete=models.CASCADE)
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    trainer = models.ForeignKey(Trainer, on_delete=models.RESTRICT)
    start_date = models.DateField()
    nesting_date = models.DateField()
    production_date = models.DateField()
    requested_headcount = models.IntegerField()
    starting_headcount = models.IntegerField(null=True, blank=True)
    ending_headcount = models.IntegerField(null=True, blank=True)
    end_nesting_headcount = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return str(self.program) + ' ' + str(self.project) + ' ' + str(self.start_date)


class Trainee(models.Model):
    first_name = models.CharField(max_length=55)
    last_name = models.CharField(max_length=55)
    employee_number = models.IntegerField()
    hire_date = models.DateField()
    is_term = models.BooleanField(default=False)
    new_hire_training = models.ForeignKey(NewHireTraining, on_delete=models.CASCADE, default="")

    def __str__(self):
        return self.first_name + ' ' + self.last_name

views.py

class TrainingDetailsView(DetailView):
    model = NewHireTraining
    template_name = 'nht/training_details.html'
    context_object_name = 'training'
    

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['trainees'] = Trainee.objects.filter(new_hire_training = self.model.id)
        return context

Internal Server Error: /training_details/4 Traceback (most recent call last): File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\db\models\fields_init_.py", line 1823, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'

回溯 上述异常是以下异常的直接原因:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\views\generic\detail.py", line 107, in get
    context = self.get_context_data(object=self.object)
  File "C:\Users\User\Desktop\webprojects\calendar\nht\views.py", line 167, in get_context_data      
    context['trainees'] = Trainee.objects.filter(new_hire_training = self.model.id)
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\db\models\query.py", line 941, in filter
    return self._filter_or_exclude(False, args, kwargs)
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\db\models\query.py", line 961, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\db\models\query.py", line 968, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\db\models\sql\query.py", line 1393, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\db\models\sql\query.py", line 1412, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\db\models\sql\query.py", line 1347, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\db\models\sql\query.py", line 1193, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\db\models\lookups.py", line 25, in __init__
    self.rhs = self.get_prep_lookup()
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\db\models\fields\related_lookups.py", line 117, in get_prep_lookup
    self.rhs = target_field.get_prep_value(self.rhs)
  File "C:\Users\User\Desktop\webprojects\calendar\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1825, in get_prep_value
    raise e.__class__(
TypeError: Field 'id' expected a number but got <django.db.models.query_utils.DeferredAttribute object at 0x0000011EECC3B220>.

您使用 self.object 引用对象,而不是 self.model:

class TrainingDetailsView(DetailView):
    model = NewHireTraining
    template_name = 'nht/training_details.html'
    context_object_name = 'training'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['trainees'] = Trainee.objects.filter(<strong>new_hire_training=self.object</strong>)
        return context

您也可以反向访问关系,使用:

class TrainingDetailsView(DetailView):
    model = NewHireTraining
    template_name = 'nht/training_details.html'
    context_object_name = 'training'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['trainees'] = <strong>self.object.trainee_set.all()</strong>
        return context