简体   繁体   English

在 django 中访问 RelatedManager 对象

[英]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.当我尝试访问mytravel.sections时,我无法访问字段distance和其他字段。 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.我不想在数据库中创建对象,因为我正在尝试进行一些预处理。

Think of the Manager as a query builder.将 Manager 视为查询构建器。 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() .经理无权访问任何特定实例的单个值,您必须使用 RelatedManager 的方法来获取 QuerySet,例如mytravel.sections.all() From there you will have a QuerySet that you can iterate through to get each mysection and access distance from there.从那里您将拥有一个 QuerySet,您可以遍历它以获取每个 mysection 并从那里访问距离。

RelatedManagers ARE managers, they just have extra functionality. RelatedManagers 是经理,他们只是有额外的功能。 Now this is confusing because there also QuerySets which are similar to Managers except they have a query already stored.现在这很令人困惑,因为还有类似于 Managers 的 QuerySets,只是它们已经存储了一个查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM