首页 > 解决方案 > Django OneToOneField related name works for one Model but not another

问题描述

I have a project with common store-like functionality of Q&As and Reviews for each Item. The app is more complex than just this, but this is the boiled down crux of the issue. Here is the basic model and apps setup:

# Q&As App
Class Question(models.Model):
    ...

# Reviews App
Class Review(models.Model):
    ...

# Items App
Class Item(models.Model):
    ...

Class ItemQuestion(models.Model):
    question = models.OneToOneField(Question, related_name='item_question')
    item = models.ForeignKey(Item, related_name='questions')
    ...

Class ItemReview(models.Model):
    review = models.OneToOneField(Review, related_name='item_review')
    item = models.ForeignKey(Item, related_name='reviews')
    ...

This issue comes when using the reverse look ups:

Question().item_question # Raises Question.item_question.RelatedObjectDoesNotExist: Question has no item_question
Review().item_review # Returns ComponentReview instance                                                                               

detailed stack trace:

Traceback (most recent call last):
  File ".../site-packages/django/db/models/fields/related_descriptors.py", line 415, in __get__                                                                                        
    self.related.get_accessor_name()
Question.item_question.RelatedObjectDoesNotExist: Question has no item_question

I'm not interested in design decision alternatives or anything like that, but more trying to understand why this is happening. Looking at the model setup and the migration files, everything seems identical in terms of code implementation, so why does one reverse lookup work and not the other? How can I get both to work?

Thanks!

Django Version 2.2

标签: pythondjangodjango-modelsone-to-one

解决方案


推荐阅读