0

I have the following data structure

class A(models.Model):
   a number of fields here

class AbstractParent(models.Model):
   some fields here

   class Meta:
       abstract = True

class B(AbstractParent):
   a = ForeignKey(A, null=True,default=None, blank=True, on_delete=models.SET_NULL)

I would expect to access the object of B class that fk to an instance of A a via a.b_set or a.bs_set however I only get the error that attribute b_set does not exist for a. Any ideas why this is possible and how to access b that references a via a itself?

Daniel Kislyuk
  • 956
  • 10
  • 11
  • 1
    Can you access `a` from `B` instances? What is the output of `A._meta.related_objects` and `B._meta.related_objects`? – Endre Both Apr 15 '19 at 18:13
  • You should probably show your real code. This is likely dependent on something you're not showing us. – Daniel Roseman Apr 15 '19 at 18:18
  • That should work. Have you tried setting a related name on the foreign key and using that? – Mikey Lockwood Apr 15 '19 at 18:24
  • @EndreBoth yes, accessing a from b instances works fine. b.a returns an object, to which b fk's. b._meta.related_objects is expectedly empty, while a._meta.related_objects returns a whole bunch of relations (it's a big project) including . – Daniel Kislyuk Apr 16 '19 at 06:51
  • @DanielRoseman I'd love to show the code, but it's a large closed-source project. – Daniel Kislyuk Apr 16 '19 at 06:52
  • @mikeyj this can be fixed, but I'd really love to understand how it is possible in the first place. – Daniel Kislyuk Apr 16 '19 at 06:54
  • 1
    Then run `A._meta.related_objects[x].related_name` for a surprise (`x` being the appropriate numerical index for the `` relation; you can also run a `for ... in`. – Endre Both Apr 16 '19 at 07:12
  • Wait, is A's related object `` or ``? It should be the latter (the former would imply a fk relationship to self). – Endre Both Apr 16 '19 at 08:32
  • @EndreBoth surprising indeed, `related_name` was `None` =) – Daniel Kislyuk Apr 17 '19 at 07:07
  • Fascinating (but it only means that no `related_name` is set as a field option). I assume that it works fine if you set a related name on `B.a`? – Endre Both Apr 17 '19 at 13:56

0 Answers0