I'm using Django 1.8.3 with Rest Framework and json-api (https://github.com/django-json-api/django-rest-framework-json-api). I have this OneToOne Relationship:
class CalendarBlock(models.Model):
vehiclecheck = models.OneToOneField('vehiclecheck.VehicleCheck',
null=True, blank=True,
related_name='calendar_block'
)
[...]
class VehicleCheck(models.Model):
[...]
Now the problem is, the relationship can be "empty". Which works, when going from CalendarBlock to Vehiclecheck, but not in the reverse relationship:
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.
Edit: My main problem is that since I'm using rest_framework, I can't use exception handling or the like because I don't call access the data explicitly.
Django has some issues regarding OneToOne and ForeignKey related fields. Concretely assuming:
class A(Model):
# assume these models exist
b = ForeignKey(B, null=True)
c = ForeignKey(C)
d = OneToOneField(D, null=True, related_name="a")
e = OneToOneField(E, related_name="a")
The examples I gave you are related to design decision in the framework, and not bugs. Also, the important fact is not that they are new instances, but that they have empty references (or no O2O is referencing them, respectively). Summary:
clean(self) and perhaps the user did not populate such field, and you retrieve it. The same applies for OneToOne.Every CalendarBlock instance will have vehiclecheck either null or not null according to your definition, the same doesn't apply for VehicleCheck instances, you are gonna have to check for that first so you can avoid the RelatedObjectDoesNotExist. You can do something like this:
vehicle_check = VehicleCheck.objects.get(pk=398)
if hasattr(vehicle_check, 'calendar_block'):
calendar_block = vehicle_check.calendar_block
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With