python/django:模型对象没有属性'prefetch_related' [英] python/django: model object has no attribute 'prefetch_related'

查看:33
本文介绍了python/django:模型对象没有属性'prefetch_related'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个模型"VehicleDetails",用户可以在其中填写车辆的详细信息,还创建了另一个模型"TripStatus",在该模型中,他可以更新车辆的位置.我想获得我在以下代码中所做的最新位置.我在视图中使用prefetch_related来返回特定车辆的位置值.但是,在运行服务器后,它将引发错误:"TripStatus对象没有属性'prefetch_related'".我很乐意帮助我解决这个问题.models.py:

I have created a model 'VehicleDetails' in which a user can fill the details of a vehicle and another model 'TripStatus' in which he updates the vehicle location. I wanted to get the latest location for which i did as in my below code. I use prefetch_related in my view to returns the location values for a particular vehicle. But, when after running the server, it raises an error : "TripStatus object has no attribute 'prefetch_related'". I would appreciate helping me solve this. models.py:

class VehicleDetails(models.Model):
    Vehicle_No = models.CharField(max_length=20)

class TripStatus(models.Model):
    vehicledetails = models.ForeignKey(VehicleDetails, related_name='statuses')
    CHOICES = (('Yet to start', 'Yet to start'),('Trip starts', 'Trip starts'), ('Chennai','Chennai'), ('Vizag', 'Vizag'), ('Kolkata', 'Kolkata'))
    Vehicle_Status = models.CharField(choices=CHOICES, default="Yet to start", max_length=20)
    statustime = models.DateTimeField(auto_now=False, auto_now_add=True)

views.py:

def status(request):
    tripstatus = TripStatus.objects.all().latest('statustime').prefetch_related('statuses')
    context = {
        "tripstatus": tripstatus,
    }
    return render(request, 'loggedin_load/active_deals.html', context)

模板:

{% for status in vehicledetails.statuses.all %}
{{status.Vehicle_Status}}
{% endfor %}

推荐答案

prefetch_related在queryset对象上起作用.最新返回单个模型而不是查询集.

prefetch_related works on a queryset object. Latest returns a single model not a queryset.

这应该有效:

tripstatus = TripStatus.objects.all().prefetch_related('statuses').latest('statustime')

这篇关于python/django:模型对象没有属性'prefetch_related'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆