Add a column from another object to an existing listview

141 Views Asked by At

I have an existing listview and I want to add a new column(contactDate) from another object which will be soratble. I want to sort my LeftListView by the contact_date of the Action each Left record contains. my objects are:

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

My listview is as above:

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

The result should somehow be as below:

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

As a newbie in python I haven't found a good example that fits my solution till now. Any orientation is well-appreciated.

0

There are 0 best solutions below