如何使用基于类的视图的djando-table2来显示来自多个表的数据?

时间:2017-07-27 08:18:27

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

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

抱歉英语不好。

谢谢

1 个答案:

答案 0 :(得分:0)

这里有两个问题。

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

第二个方法是,应通过向Participant模型中的DailyRecord添加属性“ related_name”到daily_record向后与Participant相关,如下所示:

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')