Access RelatedManager object in django

3.8k Views Asked by At

I have the following model :

class Travel(models.Model):
    purpose = models.CharField(max_length=250, null=True)
    amount = models.IntegerField()
class TravelSection(models.Model):
    travel = models.ForeignKey(Travel, related_name='sections', on_delete=models.CASCADE)
    isRoundTrip = models.BooleanField(default=True)
    distance = models.FloatField()
    transportation = models.CharField(max_length=250)

I create object without using the database :

mytravel = Travel(
  purpose='teaching',
  amount=1
)
mysection = TravelSection(
  travel=mytravel,
  isRoundTrip=True,
  distance=500,
  transportation='train'
)

When I try to access mytravel.sections, I can't access to the field distance and other fields. How can I do this without having to save in the database? I don't want to create objects in the database, because I'm trying to make some preprocessing.

1

There are 1 best solutions below

0
On

Think of the Manager as a query builder. Managers do not have access to individual values for any particular instance, you must use the RelatedManager's methods to get a QuerySet such as mytravel.sections.all(). From there you will have a QuerySet that you can iterate through to get each mysection and access distance from there.

RelatedManagers ARE managers, they just have extra functionality. Now this is confusing because there also QuerySets which are similar to Managers except they have a query already stored.