1

I've recently upgraded one of my Django projects from 1.9.6 to 2.2 and in doing so I'm getting a strange error around a specific ForeignKey relation.

models.py

class MyObject1(models.Model):
    myobject2 = models.ForeignKey(MyObject2, on_delete = models.CASCADE)

views.py

def my_view(request, id):
    try:
        my_object = MyObject1.objects.get(id = id)
    except:
        # do some stuff
    else:
        print (my_object.myobject2)

result

RelatedObjectDoesNotExist

MyObject1 has no myobject2

at line print (my_object.myobject2)

I have confirmed via the Django shell that the instance in question does have a valid myobject2 and I don't get that error when performing the same actions in the shell.

All other ForeignKey relations in the application work as expected except for this one.

This is quite puzzling and all help is appreciated. Thanks!

apardes
  • 4,272
  • 7
  • 40
  • 66
  • 2
    What does `print (my_object.myobject2_id)` output? – Alasdair Apr 23 '19 at 15:20
  • @Alasdair It throws the error I mentioned. I would just expect it to print a `None` value but that's not the case. – apardes Apr 23 '19 at 16:34
  • Please post the full traceback. I don't think your example code is enough to explain what's going on. – Alasdair Apr 23 '19 at 16:35
  • 1
    As an aside, Django 1.9 to Django 2.2 is a big leap. It might be better to upgrade to Django 1.11 LTS, fix any deprecation warnings, then upgrade to Django 2.2. That way you'll get to see deprecation warnings that you might otherwise miss, and you'll narrow down when the changes in Django occurred that are affecting your app. – Alasdair Apr 23 '19 at 16:38
  • Have you tried running showmigrations to see if some unexpected error shows up? – gdef_ Apr 23 '19 at 16:54

0 Answers0