Best way to avoid RelatedObjectDoesNotExist on row_result.object_repr attribute initialisation
See original GitHub issueHello, 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:
- Created 7 years ago
- Reactions:3
- Comments:6 (4 by maintainers)
Top 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 >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Regarding the importing of
RelatedObjectDoesNotExist
, it’s actually a property of Django’sReverseSingleRelatedObjectDescriptor
which, if you look at the code, raises actually theDoesNotExist
of the related field, which has for base classObjectDoesNotExist
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:This should be fixed in master now.