python - 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
解决方案
推荐阅读
- mongodb - 有没有办法在 mongoDB 中获取日志以及用户 ip 地址的任何操作?
- visual-studio - 构建后事件命令行:xcopy ERROR
- elasticsearch - 无法在弹性 7.5.1 中启动 Packetbeat
- jquery - 如何制作平滑的块外观?
- javascript - 根据单选按钮选择打开下拉菜单
- java - 防止 Spring Boot 缓存文件
- javascript - List.js 搜索对象?
- java - 使用 tess4j 库的 Tesseract OCR
- ubuntu-16.04 - ROS-Kinetic:无效标签:无法加载命令参数:命令返回代码 [1]
- javascript - 列表中新添加的项目不是 React 中的重新渲染组件