Reputation: 695
I have two MySQL models:
class registration(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField()
password = models.CharField(max_length=30)
company = models.CharField(max_length=30)
class personal_details(models.Model):
reg = models.ForeignKey(registration)
job = models.CharField(max_length=30)
experience = models.IntegerField(default=0)
I want to filtering details using both experience and company as a keyword. I want to fetch and display details(name, email, company, job, experience) from both tables in my HTML page.
Upvotes: 2
Views: 7680
Reputation: 1309
Without a more in-depth explanation of your problem, it's hard to answer your question properly, but here goes:
One option:
# views.py
def mypage(request):
details = Personal_details.objects.select_related().filter(experience=3)
names = [d.reg.name for d in details]
return render(request, 'mypage.html', {'names': names})
# html
<p>People with 3 experience:</p>
<ul>
{% for name in names %}
<li>{{ name }}</li>
{% empty %}
<li>Nobody has 3 experience!</li>
{% endfor %}
</ul>
Another option:
# views.py
def mypage(request):
details = Personal_details.objects.select_related().all()
names = [d.reg.name for d in details]
info = zip(details, names)
return render(request, 'mypage.html', {'info': info})
#html
<ul>
{% for detail, name in info %}
{% if detail.experience == 0 %}
<li>{{ name }} has 0 experience</li>
%{ elif detail.experience == 1 %}
<li>{{ name }} has 1 experience</li>
# and so on and so forth....
{% endif %}
{% endfor %}
</ul>
Note how I capitalised your model (i.e. class) names. This is convention and you should stick to it.
So this may or may not be what you are hoping to do, and it probably isn't the best way to go about it, but hopefully it will get you started on your own solution. I recommend reading up on Django views and template tags.
Upvotes: 2
Reputation: 22808
details = personal_details.objects.filter(experience=1,
reg__company="YourCompany").select_related()
{% for detail in details %}
Name: {{ detail.reg.name }}
Email: {{ detail.reg.email }}
Company: {{ detail.reg.company }}
Job: {{ detail.job }}
Experience: {{ detail.experience }}<br/>
{% endfor %}
Upvotes: 3
Reputation: 47172
Not sure what you want data wise, but you can pull the data from the personal_details
objects ForeignKey relationship in two ways.
With reverse relationship go via the _set
and I'm just shooting from the hip here:
reg = registration.objects.get(pk=1)
print reg.personaldetails_set.job
Otherwise, via the normal FK way.
details = personal_details.objects.get(pk=1)
print details.reg.name
Upvotes: 0
Reputation: 838
First get a list of personal_details (with experience qual to 9) like this:
p_details_list = personal_details.objects.filter(experience=9)
After that you can acces each element's reg
attribute, and it will give you the corresponding registration
object
Upvotes: 1