【发布时间】:2016-08-30 23:56:55
【问题描述】:
我确实将项目从 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?
【问题讨论】:
-
[3]中的代码没有意义,因为与Trace关联的TracePoint可能不止一个。 -
是的,TracePoint 可能比与 Trace 关联的要多,但在旧 Django 中它确实有效...
-
那将是旧版本中的一个错误。
-
我在DetailView中也有这个bug,DetailView使用get_related_selections,当然我得到“FieldError: Invalid field name...”,为了避免错误我必须使用ManyToManyField而不是ForeigenKey?跨度>
标签: django django-select-related