在Django中过滤查询时,对象没有属性' meta'

o0lyfsai  于 2023-07-01  发布在  Go
关注(0)|答案(1)|浏览(121)

这是我第一次遇到这个问题,错误说

'TevList' object has no attribute 'META'

我尝试将.first()放在filter之后,但错误仍然存在
views.py

@csrf_exempt
def tevemployee(request):
    tev_id = request.POST.get('tev_id')
    qs_list = TevList.objects.filter(id=tev_id).first()
    return JsonResponse({'data': list(qs_list)})
  • AJAX **
$('.item-details').click(function (event) {
let id = $(this).attr("id");
  $.ajax({
    type: "POST",
    url: "{% url 'tev-employee' %}",
    data:{
        tev_id : id
    }
    }).done(function(data){

  });

models.py

class TevList(models.Model):
employee_name = models.CharField(max_length=128,blank=True, null=True)
original_amount = models.FloatField(null=True, blank=True, default=0)
status = models.CharField(default="On-going",max_length=128,blank=True, null=True)
incoming_remarks = models.CharField(max_length=255, blank=True, null=True)
correctness_remarks = models.CharField(max_length=255, blank=True, null=True)
date_in = models.DateTimeField(default=datetime.now,blank=True, null=True)
date_out = models.DateTimeField(blank=True, null=True)
deleted_at = models.DateTimeField(blank=True, null=True)
user_id = models.BigIntegerField(blank=True, null=True)

class Meta:
    managed = True
    db_table = 'tev_list'
zrfyljdw

zrfyljdw1#

问题似乎出在views.py中的tevemployee视图函数中。当您尝试使用list(qs_list)将qs_list对象转换为列表时,它会导致错误,因为qs_list是TevList模型的单个示例,而不是列表或可迭代对象。
将对象序列化为JSON并使用字典:

from django.core import serializers

@csrf_exempt
def tevemployee(request):
    tev_id = request.POST.get('tev_id')
    qs_list = TevList.objects.filter(id=tev_id).first()

    # Check if the record exists
    if qs_list:
        # Serialize the object into JSON
        data = serializers.serialize('json', [qs_list])
        # Convert the serialized data to a dictionary
        data_dict = json.loads(data)[0]['fields']
        return JsonResponse({'data': data_dict})
    else:
        return JsonResponse({'error': 'Record not found'})

相关问题