I have a model, Code, with a recursive foreign key to itself (‘self’). This field is called ‘childof’, and is meant to model a hierarchy in Code, i.e., section1 is a childof chapter2, so section1.childof returns chapter2.
Therefore, chapter2.code_set should return section1 and its siblings. However, I have overridden code_set with the related_name ‘parent’ on the childof field. Nevertheless, both parent and code_set appear in dir() - as does childof. There is no ‘childof_set’ or ‘self_set’ in dir().
Here is my problem: chapter2.parent returns a Manager object. But chapter2.parent.all() returns the ‘Manager cannot be accessed by instances’ error. My best guess is that this is happening because chapter2 is itself a childof subtitle3, but that’s just a guess.
The same error occurs with chapter2.code_set. Here is the relevant portion of my model code and some actual samples from the repl.
childof = models.ForeignKey(
'self', on_delete=models.CASCADE, related_name='parent', blank=True, null=True,
default=None)
cg = Code.objects.filter(short_arrow__startswith="TITLE 14-COAST GUARD")
cg1 = Code.objects.get(pk='287ea0df')
cg1
<Code: TITLE 14-COAST GUARD USCE SUBCHAPTER III-PROCUREMENT>
cg2 = Code.objects.get(short_arrow__contains='CHAPTER 11-ACQUISITIONS')
cg2
<Code: TITLE 14-COAST GUARD USCE CHAPTER 11-ACQUISITIONS>
cg2.childof
<Code: TITLE 14-COAST GUARD USCE SUBTITLE I-ESTABLISHMENT, POWERS, DUTIES, AND ADMINISTRATION>
cg2.parent
<django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager at 0x7f17f4b49df0>
cg1.childof
<Code: TITLE 14-COAST GUARD USCE CHAPTER 11-ACQUISITIONS>
cg1.childof == cg2
True
cg2.parent.all()
Out[18]: Traceback (most recent call last):
...
AttributeError: Manager isn't accessible via Code instances
cg2.code_set()
Traceback (most recent call last):
...
AttributeError: 'RelatedManager' object has no attribute 'code_set'
cg2.parent.count
<bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.db.models.fields.related_descriptors.create_reverse_many_to_one_manager.<locals>.RelatedManager object at 0x7f17f4b49430>>
cg2.parent.count()
Traceback (most recent call last):
...
AttributeError: Manager isn't accessible via Code instances
cg4 = cg.select_related().filter(short_arrow__contains='CHAPTER 11-ACQUISITIONS')
cg4
<QuerySet [<Code: TITLE 14-COAST GUARD USCE CHAPTER 11-ACQUISITIONS>]>
I have two other recursive fk to self, one without a related name:
approval = models.ForeignKey(
'self', on_delete=models.PROTECT, blank=True, null=True, default=None)
And one with:
authorizing_statute = models.ForeignKey(
'self', on_delete=models.PROTECT, related_name='source_statute', blank=True, null=True, default=None)
My code passes check and I am not getting any accessor errors.
Please advise. Thanks.