0

I have 2 models in my app -

In models/parent.py I have -

 from django.db import models
 class Parent(models.Model): 
       class Meta:
          db_table = "parent_table"
       start_date = models.DateField()
       end_date = models.DateField()

In models/child.py I have -

from django.db import models
from models.parent import Parent
class Child(models.Model): 
   class Meta:
      db_table = "child_table"
   some_ref = models.ForeignField(Parent)

Now in models/parent.py I am defining a property as -

@property
def referred_values(self):
 return self.child_set.all()

It gives me error -

AttributeError: 'Parent' object has no attribute 'child_set'

But if I import Child class in any file in my app, it works fine. Is this an expected behaviour or am I missing something here?

Thanks in advance.

DUDE_MXP
  • 724
  • 7
  • 24

1 Answers1

3

It is good to set related_name directly

some_ref = models.ForeignField(Parent, related_name='childs')

and use childs insted of child_set (more English)

Also you can use:

 some_ref = models.ForeignField(to='parent_app.Parent', related_name='childs')

and you do not need import Parent to Child models

Also:

class Parent(models.Model): 

insted of

 class Parent:

But in your probrem, I think you forget add Child to models/__init__.py

Andrei Berenda
  • 1,946
  • 2
  • 13
  • 27
  • Using related_name worked !! Thanks. It would be nice if you can give some insight on why it didn't work without using related_name. – DUDE_MXP May 22 '18 at 19:35
  • I think, you forget add your model to models/__init__.py and django do not know about it untill you import it – Andrei Berenda May 23 '18 at 07:13