Reputation: 2949
I have these two models
class Upload(models.Model):
name=models.CharField(max_length=100)
email=models.EmailField(max_length=50)
class Text(models.Model):
texts=models.CharField(max_length=500,null=True,blank=True)
upload_text=models.ForeignKey(Upload, blank=True, null=True, on_delete = models.CASCADE)
What I want is to get texts
from Text
when I filter name
from Upload
. So I want name
, email
and texts
displayed.
I know this question has been asked previously and I am also doing the same, but getting error.
I have tried this
data=Text.objects.filter(upload__name__icontains=query)
But it give me an error
Cannot resolve keyword 'upload' into field. Choices are: id, texts, upload_text, upload_text_id
I have also tried this.
data=Upload.objects.filter(name__icontains=query)
data1=Text.objects.filter(upload_text__in=data)
But I am unable to display both at the same time in jinja2 template.
{% for q,t in zip(query_key,query_res) %}
{{ t.texts }} {{ q.name }} | {{q.email}}
Upvotes: 1
Views: 821
Reputation: 4095
You have a little mistake instead of upload__name
its upload_text__name
:
data=Text.objects.filter(upload_text__name__icontains=query)
And, your template:
{% for text in data %}
{{ text.texts }} {{ text.upload_text.name }} | {{text.upload_text.email}}
Upvotes: 2
Reputation: 476544
I think you make things too complicated, you can just fetch the objects with:
data = Upload.objects.filter(name__icontains=query).prefetch_related('text_set')
and in the template, you can then iterate over the data, and obtain the related Text
s with .text_set
:
{% for upload in data %}
{% for t in upload.text_set.all %}{{ t.texts }}{% endfor %} {{ upload.name }} | {{ upload.email }}
{% enfor %}
Upvotes: 0