question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Best way to avoid RelatedObjectDoesNotExist on row_result.object_repr attribute initialisation

See original GitHub issue

Hello, I have 2 models:

class Candidate(models.Model):
    first_name = models.CharField(_("First name"), max_length=255)

class Test(models.Model):
    candidate = models.OneToOneField(Candidate)

    def __str__(self):
        return self.candidate.first_name

In Test model candidate is required field and I want to show first_name in Django admin (in selects, for example)

When I try to import data for Test model, I get RelatedObjectDoesNotExist. This line of code https://github.com/django-import-export/django-import-export/blob/master/import_export/resources.py#L414 throw an Exception for newly created instances, before I can skip invalid rows.

Do you have any best practices to avoid this kind of error on import? I’m not sure that I really like an idea always check FK existence in __str__ method to fix this behaviour, but can’t think of something better. Thanks.

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:3
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
browniebrokecommented, Aug 25, 2016

Regarding the importing of RelatedObjectDoesNotExist, it’s actually a property of Django’s ReverseSingleRelatedObjectDescriptor which, if you look at the code, raises actually the DoesNotExist of the related field, which has for base class ObjectDoesNotExist

class ReverseSingleRelatedObjectDescriptor(object):

    @cached_property
    def RelatedObjectDoesNotExist(self):
        return type(
            str('RelatedObjectDoesNotExist'),
            (self.field.rel.to.DoesNotExist, AttributeError),
            {}
        )

To complete @JarnoRFB comment above, I think the try-except should be limited to this exception in the __str__ (or __unicode__ in python 2) like below, and return something safe and recognisable in case of failure:

from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import models

class MyModel(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)

    def __unicode__(self):
        try:
            return "{0}".format(self.user)
        except ObjectDoesNotExist:
            return "[MyModel instance]"
1reaction
jschneiercommented, Sep 13, 2016

This should be fixed in master now.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Django check if a related object exists error - python
Use hasattr(self, 'customers') to avoid the exception check as recommended in Django docs: def has_related_object(self): return hasattr(self, ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found