简体   繁体   中英

Access model field from other model

I have three models i need to access model 1 field from model 3

class Event(models.Model):
    custom_title = models.CharField(max_length=255, blank=True, default='')

class SubEvent(models.Model):
    event = models.ForeignKey(
    'Event',
    related_name='events',
    on_delete=models.CASCADE
)

class Notice(models.Model)
      event = models.ForeignKey('Event', related_name='notices', 
                  on_delete=models.CASCADE)

I need to access SubEvent model data from Notice model is that possible?

Yes you can.

Exactly how depends on which SubEvent you want, but I presume you follow the foreign key from notice to event from where you have access to its (potentially multiple) events . So you might query

self.event.events.filter(
    # criteria to identify  particular SubEvents
    ...)

or just

self.event.events.all()

or fetch one, such as the latest:

latest_subevent = self.event.events.latest()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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