Django ForeignKey class not found

I created the following ForeignKey field in my model under a class called "Activity"

related_workoutrecord = models.ForeignKey(WorkoutRecord, null=True, blank=True) 

The ForeignKey belongs to the WorkoutRecord class, which must be empty.

After adding this column, I ran south and received the following error message:

 NameError: name 'WorkoutRecord' is not defined 

Any thoughts on what's going on? I confirmed that "WorkoutRecord" is a class in my model.

Is it necessary to write WorkoutRecord as a string (with quotes), for example:

 related_workoutrecord = models.ForeignKey('WorkoutRecord', null=True, blank=True) 

I appreciate the feedback

+6
source share
4 answers

According to my comment, make sure the Activity class has access to the WorkoutRecord class.

An error means that it says that WorkoutRecord is not defined in your Activity class.

First check these two things:

1) Have you imported it?

2) Was the WorkoutRecord defined before the Activity?

+8
source

The WorkoutRecord class must be defined before (i.e., above) the Activity class in order to use the reference to the class without quotes. If circular links exist between classes, then using the quoted string will work to get a lazy reference to the class defined later in your code.

+3
source

You have two options:

  • You can import the WorkoutRecord model from any module it is in (this is the standard python approach)

     from myapp.models import WorkoutRecord related_workoutrecord = models.ForeignKey(WorkoutRecord, null=True, blank=True) 

    Using this approach, sometimes you can get into a situation where you have cyclic imports, so there is an alternative:

  • You can use the string as the first argument to ForeignKey or ManytoManyField to indicate the model with which you want to establish relationships. This is a django function. If you look at the documentation for the ForeignKey relationship , it says:

    If you need to create a relation to a model that is not yet defined, you can use the model name, not the model object itself:

    This means that if the model is not yet defined, but is in the same module (i.e. below the current code), you can simply use the model name in quotation marks: 'WorkoutRecord' , but if the model is in another application / module, you can also indicate this as a string: 'myapp.WorkoutRecord'

+1
source

Use the format 'yourapp.Model' .

 foo = models.ForeignKey('yourapp.WorkoutRecord', null=True, blank=True) 

With quotes.

0
source

Source: https://habr.com/ru/post/943478/


All Articles