我使用Django 1.8.3與Rest Framework和json-api(https://github.com/django-json-api/django-rest-framework-json-api)。我有這個OneToOne關係:Django OneToOne反向關係DoesNotExists當爲空
class CalendarBlock(models.Model):
vehiclecheck = models.OneToOneField('vehiclecheck.VehicleCheck',
null=True, blank=True,
related_name='calendar_block'
)
[...]
class VehicleCheck(models.Model):
[...]
現在問題是,關係可以是「空的」。其中一期工程,從CalendarBlock去Vehiclecheck的時候,而不是在相反的關係:
In [1]: from vehiclecheck.models import VehicleCheck
In [2]: from dispo_calendar.models import CalendarBlock
In [3]: CalendarBlock.objects.first().vehiclecheck
In [4]: # no problem here
In [5]: VehicleCheck.objects.first().calendar_block
Out[5]: <CalendarBlock: CalendarBlock object>
In [6]: VehicleCheck.objects.get(pk=398).calendar_block
---------------------------------------------------------------------------
RelatedObjectDoesNotExist Traceback (most recent call last)
<ipython-input-6-65d3178686f5> in <module>()
----> 1 VehicleCheck.objects.get(pk=398).calendar_block
/home/sh/gitty/work/tcs_cardispo2_backend/.venv/lib/python3.5/site-packages/django/db/models/fields/related.py in __get__(self, instance, instance_type)
468 "%s has no %s." % (
469 instance.__class__.__name__,
--> 470 self.related.get_accessor_name()
471 )
472 )
RelatedObjectDoesNotExist: VehicleCheck has no calendar_block.
編輯:我的主要問題是,由於我使用rest_framework,我不能使用異常處理或類似因爲我不明確地調用訪問數據。
我不能這樣做,因爲我使用序列化程序和ModelViewSet,所以數據被這些庫「自動」獲取。 – arsenbonbon