将另一个对象的列添加到现有列表视图

时间:2018-11-22 15:42:04

标签: django python-2.7 listview django-1.3

我有一个现有的列表视图,我想从另一个可以添加的对象中添加一个新列(contactDate)。我想按每个Left记录包含的Action的contact_date对我的LeftListView进行排序。 我的对象是:

class Left(models.Model):
   ref = models.CharField(max_length=16, blank=True)
   customer = models.CharField(max_length=100, blank=True)
   days = models.PositiveIntegerField(blank=True, null=True)
   business_classification = models.CharField(max_length=15, blank=True)
   created = models.DateTimeField(auto_now_add=True)
   modified = models.DateTimeField(auto_now=True)

  def __unicode__(self):
    return u'%s in %s (%d days)' % (
        self.customer,
        self.days_in_delay
    )
class Action(models.Model):
  left = models.ForeignKey(Left, related_name='actions')
  personal_use = models.ForeignKey(User, related_name='actions')
  phone_calls = models.BooleanField(default=False)
  contact_date = models.DateTimeField(blank=True, null=True)
  description = models.CharField(max_length=100)

 def __unicode__(self):
    return self.description

我的列表视图如上所述:

class LeftListView(ListView):

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
       return super(LeftListView, self).dispatch(*args, **kwargs)

def get_queryset(self):
    for_date = self.kwargs.get('date', datetime.date.today())
    week_start, week_end = find_week_start_end(for_date=for_date)
    qs_others = Left.objects.filter(created__startswith=str(for_date))  
    qs= qs_others #| qs_cc
    reqGET = self.request.GET

@property
def querystring(self):
    params = dict(self.request.GET.items())
    for k, v in params.items():
        if not all(v):
            params.pop(k)
    has_page = params.pop('page', False)
    return '?%s' % urlencode(params)

def get_context_data(self, **kwargs):
    ctx = super(LeftListView, self).get_context_data(**kwargs)
    ctx['querystring'] = self.querystring
    for_date = self.kwargs.get('date')
    if for_date is not None:
        ctx['for_date'] = for_date
    ctx.update(search_ranges)
    ctx['filter_form'] = LeftFilterForm(self.request.GET or None,
        initial=search_ranges)
    ctx['contact_date'] = Action.objects.filter(contact_date=for_date).filter(left_ref=left.ref)

    return ctx

结果应如下所示:

No.    REF     Customer     Amount    Created Date         Days      Contact Day


1.   AB-9     Name Surname   amount    Dec 30, 2018        68        Dec 3, 2018 
2.   AB-5010  Name7 Surname7  amount    Mar 20, 2018       80            
3.   AB-78    Nametest Surnametest   amount  Dec 18, 2018   6
4.   AB-73019  Name5 Surname5   amount   Jul 08, 2018      13        Dec 3, 2018

作为python的新手,到目前为止,我还没有找到适合我的解决方案的好例子。 任何方向都很好。

0 个答案:

没有答案