gpt4 book ai didi

django - 将Django从1.6升级到1.8 : Invalid field name(s) given in select_related

转载 作者:行者123 更新时间:2023-12-04 13:10:56 25 4
gpt4 key购买 nike

我确实将项目从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")

我在Trace的DetailView中也遇到了这个错误,DetailView使用get_related_selections,当然我得到了“FieldError:Invalid field name ...”,为避免错误,我必须使用ManyToManyField而不是ForeigenKey?

最佳答案

Django 1.8 checks that the fields given in select_related are correctselect_related方法可用于外键和一对一字段。不能将它用于TraceTracePoint的反向关系。

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

您可以删除select_related()调用,或将其替换为 prefetch_related ,这将起作用。

Trace.objects.prefetch_related('trace_points')

关于django - 将Django从1.6升级到1.8 : Invalid field name(s) given in select_related,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37046472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com