将Django从1.6更新为1.8:select_related中给出的字段名称无效

时间:2016-05-05 09:00:52

标签: django django-select-related

我将项目从Django 1.6.7更新到1.8.7并且我在Django 1.8中遇到以下异常,尽管使用Django 1.6它的代码是正确的:

In[2]: from apps.route import models
In[3]: models.Trace.objects.select_related("trace_points")
Out[3]: <repr(<django.db.models.query.QuerySet at 0x3b50c10>) failed: django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'trace_points'. Choices are: user>

我的模特:

class Trace(SocialMixin, models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='traces')
    name = models.CharField(u'Название', max_length=255)
    rating = RatingField(range=5, weight=0)
    start_date = models.DateTimeField(u'Дата старта')
    finish_date = models.DateTimeField(u'Дата окончания', null=True, blank=True)
    distance = models.DecimalField(max_digits=15, decimal_places=6, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    hits = generic.GenericRelation(HitCount, object_id_field='object_pk')
    description = models.TextField(null=True, blank=True)

class TracePoint(models.Model):
    country = models.ForeignKey(Country, null=True, blank=True)
    city = models.ForeignKey(City, null=True, blank=True)
    trace = models.ForeignKey(Trace, related_name="trace_points")

我也有这个错误进入TraceView上的DetailView,DetailView使用了get_related_selections,当然我得到了#34; FieldError:无效的字段名称...&#34;,为了避免错误我必须使用ManyToManyField而不是ForeigenKey ?

2 个答案:

答案 0 :(得分:10)

Django 1.8 checks that the fields given in select_related are correctselect_related方法可用于外键和一对一字段。无法将其用于反向关系Trace返回TracePoint

在之前版本的Django中,Trace.objects.select_related("trace_points")不会引发错误,但select_related()调用无效。

您可以删除select_related()来电,也可以将其替换为prefetch_related,这将有效。

Trace.objects.prefetch_related('trace_points')

答案 1 :(得分:3)

Django&#39; select_related()对后退外键关系不起作用。

您可能希望使用prefetch_related()来预取python级别的所有跟踪点。

models.Trace.objects.prefetch_related("trace_points")