'AutoField'对象没有属性'remote_field'

时间:2017-10-06 23:26:22

标签: python django django-rest-framework

我在Django 1.8中遇到一个奇怪的错误:

'AutoField' object has no attribute 'remote_field'

我有一个类似的模型:

from django.db import models
from django.utils import timezone


class Event(models.Model):
    product_type = models.CharField(max_length=250, null=False, blank=False)
    received_time = models.DateTimeField(editable=False)
    source_json = models.TextField()
    event_id = models.CharField(max_length=250, null=False, blank=False)

    # https://stackoverflow.com/questions/1737017/django-auto-now-and-auto-now-add
    def save(self, *args, **kwargs):
        if not self.id:
            self.received_time = timezone.now()
        return super(Event, self).save(*args, **kwargs)

    @classmethod
    def event_id_is_already_saved(cls, event_id_in_question):
        items_found = cls.objects.filter(event_id=event_id_in_question)
        if items_found:
            return True
        return False

观点如:

import json

from django.http import HttpResponse
from rest_framework import viewsets

from events.utils.elastic_db_utils import get_elastic_exact_search_from_query_dictionary
from events.serializers import EventSerializer
from events.models import Event


def list_events(request):
    all_events = Event.objects.all()
    serialized = [EventSerializer(event) for event in all_events]
    return HttpResponse(json.dumps(serialized))


class EventViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = Event.objects.all().order_by('-received_time')
    serializer_class = EventSerializer

网址:

from django.conf.urls import url, include
from rest_framework import routers

from . import views

router = routers.DefaultRouter()
router.register(r'events', views.EventViewSet)


urlpatterns = [
    url(r"^$", views.search_elastic_db, name='search-elastic-db'),
    url(r"^events", views.list_events, name='list-events'),
    url(r'^api/', include(router.urls)),
]

我的视图集和^events端点都不起作用,都会得到相同的错误。我可以在shell中看到我的模型没有错:

In [1]: from events.models import Event

In [2]: Event.objects.all()
Out[2]: [<Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>, <Event: Event object>]

1 个答案:

答案 0 :(得分:2)

我认为您无法从您提供的代码中推断出确切的原因,但根据错误消息,您可能会在其他地方使用代码 - 可能是在第三个代码中派对图书馆 - 为较新版本的Django编写的。如上所述,in the release notes已将remote_field属性添加到Django v1.9中的Field。 (此属性显然是absent in v1.8。)

您的选择是:

  1. 将项目升级到更新的Django版本。
  2. 向第三方库移植,将有问题的Field更改为使用rel,并重写任何其他不兼容的代码。
  3. 将第三方库替换为支持Django v1.8的另一个库。
  4. (我推荐第一个选项,因为Django版本之间的升级是well-documented。)