【问题标题】:How to use djando-table2 with class based view to display data from multiple table?如何使用 django-tables2 和基于类的视图来显示来自多个表的数据?
【发布时间】:2017-07-27 08:18:27
【问题描述】:
models.py

class DailyRecordManager(models.Manager):
def get_query_set(self):
    qs = super(DailyRecordManager, self).get_query_set().order_by('date_organised')
    return qs

class DailyRecord(models.Model):
    date_organised = models.DateField('Ogransied Date', help_text=('Enter Date when the program is organised: CCYY-MM-DD'))
    program_name = models.TextField('program name',)
    venue = models.CharField('venue', max_length = 255, blank=True)
    organiser = models.ForeignKey(Organiser, verbose_name = 'Organiser', related_name = 'organisers')

    objects = models.Manager()
    public = DailyRecordManager()


    class Meta:
        verbose_name = 'dailyrecord'
        verbose_name_plural = 'dailyrecords'
        ordering = ['-date_organised']

    def __str__(self):
         return self.program_name

class Participant(models.Model):
    participant = models.CharField(max_length= 50, unique = True)
    daily_record = models.ForeignKey(DailyRecord, verbose_name = 'program_name')

    class Meta:
        verbose_name = 'participant'
        verbose_name_plural = 'participants'

    def __str__(self):
        return self.participant

views.py

class DailyActivityPageView(SingleTableView):
    table_class = DailyRecordTable
    queryset = DailyRecord.public.all() 
  # queryset = Participant(DailyRecord.public.all()) is not working
    template_name = 'dailyrecord/daily-activity-record.html'

tables.py

class DailyRecordTable(tables.Table):
    date_organised = tables.Column('Date')
    program_name = tables.Column( 'Program Name')
    venue = tables.Column( 'Venue')
    organiser = tables.Column( 'Organiser')
    participant = tables.Column( 'dailyrecord.participant')

# daily = tables.RelatedLinkColumn()

    class Meta:
        model = DailyRecord

现在我需要显示参与者表中的数据,对应daily_record外键。

Click this link to view the snapshot. see the last column of the table. I need the data of Participant.partcipant column here

抱歉英语不好。

谢谢

【问题讨论】:

    标签: django python-3.x django-tables2


    【解决方案1】:

    这里有两个问题。

    首先,每日记录可以有多个参与者。因此,为了填充最后一列,您必须将所有可能的参与者聚合到该列中(例如作为列表)。

    其次,您应该通过在 Participant 模型中将属性“related_name”添加到 daily_record 来使 Participant 向后关联到 DailyRecord,如下所示:

    daily_record = models.ForeignKey(DailyRecord, verbose_name = 'program_name', related_name="participants")
    

    现在,您应该像这样从 daily_record 中获取参与者:

    participants = DailyRecord.public.first().participants.all()
    

    如果您有 OneToOneField 而不是 ForeignKey,您可以像这样将(单个)参与者添加到表中:

    participant = tables.Column( "Participant", accessor='participant')
    

    【讨论】:

      猜你喜欢
      • 2015-06-15
      • 2015-02-20
      • 1970-01-01
      • 2011-12-23
      • 1970-01-01
      • 2014-04-01
      • 2021-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多