通过queryset将模型的一个字段链接到另一个字段

时间:2017-11-12 16:10:48

标签: python django

我有一个会话变量,用于存储模型的ID。我现在想要通过模型的名称而不是id来过滤查询集。目前它只按其与名称进行比较的ID进行过滤。如何让它使用名称而不是ID。

模板链接

<td><a class="btn btn-info" href="{% url 'nodisoapp:select' company.id  %}">Working Page</a></td>

网址

url(r'^select/(?P<company_id>\d+)/$', views.comp_select, name='select'),

厂景

def comp_select(request, company_id):
    request.session['company'] = company_id
    return redirect('nodisoapp:working',company_id)

过滤视图

class LeadListView(LoginRequiredMixin, generic.ListView):
     login_url = '/scrty/login/'
        template_name = "nodiso/leadslist.html"
        model = models.Leads
        def get_context_data(self, **kwargs):
            ctx = super(LeadListView, self).get_context_data(**kwargs)
            ctx['company']= models.Company.objects.all()
            return ctx
        def get_queryset(self):
            return models.Leads.objects.filter(company=self.request.session['company'])

父模型

class Company(models.Model):
    user = models.ManyToManyField(settings.AUTH_USER_MODEL)
    name = models.CharField(max_length=265, blank=True)
    tel = models.IntegerField(blank=True, null=True)
    email = models.EmailField(max_length=265,blank=True)
    address = models.TextField(blank=True)
    postal = models.TextField(blank=True)
    regno = models.CharField(max_length=265,blank=True)
    vatno = models.CharField(max_length=265,blank=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('nodisoapp:home')

儿童模型

class Leads(models.Model):
    company = models.ForeignKey(Company)
    user = models.ManyToManyField(settings.AUTH_USER_MODEL)
    name = models.CharField(max_length=265)
    email = models.EmailField(max_length=265)
    tel = models.IntegerField()
    dateenq = models.DateField(blank=True,null=True)

    def get_absolute_url(self):
        return reverse('nodisoapp:leadlist')

    def __str__(self):
        return self.name

1 个答案:

答案 0 :(得分:0)

我找到了解决方案

def comp_select(request, company_id):
    comp = models.Company.objects.get(id=company_id)
    request.session['company'] = comp.name
    request.session['compid'] = company_id
    return redirect('nodisoapp:working',company_id)