indianLeo
indianLeo

Reputation: 153

Fetching multiple entries of same id in django

I am trying to make a query and retrieve all the data listed under that particular user with the help of the primary key. I am getting the data but it consists of only one data but I should get three.

Here is the views:

def eachlead(request, pk):
    # print(pk)
    lead = Lead.objects.get(id=pk)
    leadinfo = LeadDetail.objects.filter(id=pk)
    print(list(leadinfo))
    return render(request, "onelead.html", {'lead': lead, 'leadinfo': leadinfo})

Here is models:

class LeadDetail(models.Model):
    Lead = models.ForeignKey(Lead, on_delete=models.CASCADE)
    files = models.FileField(blank=True, upload_to='media')
    tasks = models.TextField(max_length=1000)

    def __str__(self):
        return self.Lead.first_name 

class Lead(models.Model):
    lead_status = (
        ('Potential', 'Potential'),
        ('Prospect', 'Prospect'),
        ('Negotiation', 'Negotiation'),
        ('Converted', 'Converted'),
        ('Failed', 'Failed')
    )

    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    age = models.IntegerField(default=0)
    city = models.CharField(max_length=25, null=True)
    country = models.CharField(max_length=30, null=True)
    email = models.EmailField(max_length=50, null=True)
    agent = models.ForeignKey('Agent', on_delete=models.CASCADE, null=True)
    status = models.CharField(max_length=15, choices=lead_status, null=True)
    avatar = models.ImageField(null=True, upload_to='media')

    def __str__(self):
        return self.first_name

The response I am getting is [<LeadDetail: Test1111>] or [{'id': 1, 'Lead_id': 1, 'files': 'media/dummy.pdf', 'tasks': 'Meeting at 19:00 Friday'}] but there are 3 tasks under this ID:

enter image description here

Upvotes: 0

Views: 1741

Answers (2)

Biplove Lamichhane
Biplove Lamichhane

Reputation: 4095

Because you are trying to get LeadDetail from the query, but there is only one value with the pk. Instead of filtering directly via id, you have to filter with the lead.

def eachlead(request, pk):
    # print(pk)
    lead = Lead.objects.get(id=pk)
    leadinfo = LeadDetail.objects.filter(Lead=lead)

Or, you can also do:

def eachlead(request, pk):
    # print(pk)
    lead = Lead.objects.get(id=pk)
    leadinfo = LeadDetail.objects.filter(Lead__id=pk)

Refs to django queryset.

Upvotes: 1

Alex Valenchits
Alex Valenchits

Reputation: 11

lead.leaddetail_set.all()

This more info

Upvotes: 0

Related Questions