Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access RelatedManager object in django

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.

like image 639
user1595929 Avatar asked Oct 14 '25 20:10

user1595929


1 Answers

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.

  • Regular Manager features
  • RelatedManager extra features
  • QuerySet explanation
like image 182
Kolton Noreen Avatar answered Oct 17 '25 10:10

Kolton Noreen