models.ForeignKey to model in other app

Hi, I would like to create models.ForeignKey to models in other apps, but no syntax does work.
agegroups, distances, events and member are apps under the project running_results

from django.db import models

from django.urls import reverse
import agegroups
from distances.models import Distance
from events.models import Event
from member.models import Member

class Result(models.Model):
distance_id = models.ForeignKey(distances.Distance, on_delete=models.CASCADE)
event_id = models.ForeignKey(Event, on_delete=models.CASCADE)
member_id = models.ForeignKey(Member, on_delete=models.CASCADE)
agegroup_id = models.ForeignKey(agegroups.Agegroup, on_delete=models.CASCADE)
result_value = models.IntegerField()

def get_absolute_url(self):
    return reverse("results:result-detail", kwargs={"id":})

class Meta:
    ordering = ("result_value", "name")

Error message:
File “D:\andreas\Programmierung\Python\bestenliste_laufen\running_results\results\”, line 9, in
class Result(models.Model):
File “D:\andreas\Programmierung\Python\bestenliste_laufen\running_results\results\”, line 10, in Result
distance_id = models.ForeignKey(distances.Distance, on_delete=models.CASCADE)
NameError: name ‘distances’ is not defined

How can I solve that?


If you look at the error it says:

That’s because you imported the Distance model:
from distances.models import Distance.

But then at line 10 inside your model you reference distances.Distance.

Try changing distances.Distance => Distance inside the ForeignKey definition.

Hi, thank you. It works like this

from distances.models import Distance

distance_id = models.ForeignKey(Distance, on_delete=models.CASCADE)

but Visual Studio Code says “unresolved import”