I have two tables one that stores information from a medical record and the other a second medical consultation, what I want is to make a search and if the patient had a second medical consultation shows me the information of the second medical consultation in my template, if the patient doesn't have a second medical consultation only show me the information of the medical record.
I need help and ideas on how I can do it, I'm new with Django and Python , I do the search in a view in the following way, the problem with this search is that I only see the medical record and I need that if the patient had second medical consultation to display the information.
View.py
def Expediente_Detalle(request, credencial):
Expediente_Detalle = get_object_or_404(ExpedienteConsultaInicial, credencial_consultainicial=credencial)
return render(request, 'ExpedienteDetalle.html', {'Expediente_Detalle': Expediente_Detalle})
Models.py
class ExpedienteConsultaInicial(models.Model):
credencial_consultainicial = models.CharField(max_length=10, null=True, blank=True)
def __unicode__(self):
return self.credencial_consultainicial
class ConsultasSubsecuentes(models.Model):
Consultasbc_credencial =models.ForeignKey(ExpedienteConsultaInicial,
related_name='csb_credencial')
Try:
#Models
class ExpedienteConsultaInicial(models.Model):
#max_legth=10 might be too small
credencial_consultainicial = models.CharField(max_length=100, null=True, blank=True)
def __unicode__(self):
return self.credencial_consultainicial
class ConsultasSubsecuentes(models.Model):
#related_name is name of attribute of instance of model
#to (not from!) which ForeignKey points.
#Like:
#assuming that `related_name` is 'consultations'
#instance = ExpedienteConsultaInicial.objects.get(
# credencial_consultainicial='text text text'
#)
#instaqnce.consultations.all()
#So I suggest to change `related_name` to something that will explain what data of this model means in context of model to which it points with foreign key.
consultasbc_credencial = models.ForeignKey(ExpedienteConsultaInicial,
related_name='consultations')
#View
def expediente_detalle(request, credencial):
#Another suggestion is to not abuse CamelCase - look for PEP8
#It is Python's code-style guide.
detalle = get_object_or_404(ExpedienteConsultaInicial, credencial_consultainicial=credencial)
subsequent_consultations = detalle.csb_credencial.all()
return render(request, 'ExpedienteDetalle.html', {'Expediente_Detalle': detalle, 'consultations': subsequent_consultations})
Useful links:
Following relationships backward - thats why I suggest you to
change related_name
PEP8 - and this is about CamelCase and
Python's code-style.
All you need to do is to execute another query, and provide the result to your template
def Expediente_Detalle(request, credencial):
Expediente_Detalle = get_object_or_404(ExpedienteConsultaInicial, credencial_consultainicial=credencial)
second_consultation = ExpedienteConsultaInicial.objects.filter(..)
return render(request, 'ExpedienteDetalle.html', {'Expediente_Detalle': Expediente_Detalle, 'second_consultation': second_consultation})
Then, in your template, iterate over second_consultation:
{% for c in second_consultation %}
<p> {{ c.credencial_consultainicial }} </p>
{% endfor %}
Related
I have a website which catalogs hikes, and users can log that they have gone on these hikes. I have a search function, and I want to be able to sort my list of hikes by the amount of times they have been completed by my users. I found this post which seems relevant, but is referring to a specific field in the foreignkey model, whereas I'd like to just count the total number of instances:
Django QuerySet ordering by number of reverse ForeignKey matches
Here is some sample code:
models.py:
class Hikes(models.Model)
...
class UserLog(models.Model)
user = models.ForeignKey(User, on_delete=CASCADE)
hike = models.ForeignKey(Hikes, on_delete=CASCADE)
I need to generate a queryset from my Hikes model that counts the number of times UserLog has referenced each hike, and then orders the hikes from most referenced to least. Something like this:
Hikes.objects.order_by(for each hike, count # of references in UserLog, then place in order by # of references)
So if Hike #1 has 10 UserLog instances, Hike #2 has 20, and Hike #3 has 5, the QuerySet would return:
Hike #2, Hike #1, Hike #3
Any tips?
Edit: thanks to viviwill, here is the working code in a search field:
def hike_list(request):
qs = Hikes.objects.all()
...
if request.GET:
...
searchsort = request.GET.get('sortby', '')
if searchsort == 'sortlocalrepeats':
qs = qs.annotate(count=Count('userlog')).order_by('-count')
In views:
context['rank_hike'] = Hikes.objects.annotate(number_of_hikes=Count('UserLog')).order_by('-number_of_hikes')
In the template:
{% for hike in rank_hike %}
<p>{{ hike }} {{ hike.number_of_entries }}</p>
{% endfor %}
I have created a checkbox for content filtering of products based on category.So when the user clicks on any checkbox only the books with that category should be shown.In the view I am passing the value of checkbox field(category name) obtained from the template but upon filtering, the foreign key is expecting pk(id) instead of field value.I am getting error like this,invalid literal for int() with base 10: '<category name>'.So is it possible to make foreign key accept value instead of id?
Models.py,
class Add_cat(models.Model):
category = models.CharField("Name",max_length=25,unique=True)
def __unicode__(self):
return u'{0}'.format(self.category)
class Add_prod(models.Model):
book = models.CharField("Book Name",max_length=40)
author = models.CharField("Author",max_length=30)
price = models.PositiveIntegerField("Price")
image = models.ImageField(upload_to='images',null=True)
cat = models.ForeignKey(Add_cat,on_delete=models.PROTECT)
Template file,
{% for i in products %}
<input type="checkbox" name="cat_name" value="{{i.cat}}">{{i.cat}}<br>
{% endfor %}
Views.py,
def welcome_user(request):
if 'cat_name' in request.GET:
filter_category = request.GET.get('cat_name')
my_products = Add_prod.objects.filter(cat__in = filter_category)
context = { "products":my_products}
else:
my_products = Add_prod.objects.all()
context = { "products":my_products}
return render(request,"welcome-user.html",context)
You can check in the category field itself:
my_products = Add_prod.objects.filter(cat__category__in=filter_category)
Have a look at the documentation on how this works.
Above, is only applicable if filter_category is a list. If it is a string you can filter like following:
my_products = Add_prod.objects.filter(cat__category=filter_category)
There are two things wrong with your code
You need to look up the field rather than the foreign key
By using __in you are looking the category is equal to any one of the characters in the filter_category.
Hence to fix, use the field lookup and remove the __in
Add_prod.objects.filter(cat__category=filter_category)
You can try this,it will help you:
Add_prod.objects.filter(cat__category = filter_category)
I want to display answer subject and question in my template. How would I call these variables from my Answer class in my template?
Here is how my class looks
Model.py:
class Answer(models.Model):
subject = models.ForeignKey(Subject, help_text = u'The user who supplied this answer')
question = models.ForeignKey(Question, help_text = u"The question that this is an answer to")
runid = models.CharField(u'RunID', help_text = u"The RunID (ie. year)", max_length=32)
answer = models.TextField()
def __unicode__(self):
return "Answer(%s: %s, %s)" % (self.question.number, self.subject.surname, self.subject.givenname)
def choice_str(self, secondary = False):
choice_string = ""
choices = self.question.get_choices()
for choice in choices:
for split_answer in self.split_answer():
if str(split_answer) == choice.value:
choice_string += str(choice.text) + " "
Template:
{{ subject }}
{{ question }}
{{ answer }}?????
I am fairly new to Django and I am only a few weeks in to learning.
Values to the template are passed onto by views (through something known as a context) when they render some html, and not by the model classes as you seem to be indicating.
This also makes sense because model classes are just a schema or a representation of your database, whereas views are functions that retrieve values from the database (or not) and create dynamic content to be rendered.
Here's the link to the official tutorial on how to do it properly.
Pass the values in your views.py something like this:
from django.shortcuts import render_to_response
def display_variables(request):
subject = # get your subject and assign it a variable
question = # get your question and assign it a variable
answer = # get your answerand assign it a variable
return render_to_response('your_web_page.html',{'subject':subject,'question ':question ,'answer ':answer },context_instance=RequestContext(request))
class Daily(models.Model):
rpt_date = models.DateField('Report Date', primary_key=True)
total_d_sors = models.IntegerField()
loaded_d_sors = models.IntegerField()
#diff_d_count
d_sors_missed_eod = models.CharField(max_length=300)
total_m_sors = models.IntegerField() #monthly
loaded_m_sors = models.IntegerField() #monthly
m_sors_missed_eod = models.CharField(max_length=300)
I have the above class in my models.py but when I display it through a view I need to have an additional column which will have the difference between two existing columns (total_d_sors and missed_d_sors) i.e., diff_d_count=(total_d_sors - missed_d_sors)... can someone help?
I'm seeing examples with cursor implementation; is there any other way?
Why don't you add a property on the model and calculate it on the fly as you're displaying it in your template?
class Daily(models.Model):
#property
def diff_d_count(self):
return self.total_d_sors - self.missed_d_sors
Then you can access it in your template or wherever via obj.diff_d_count.
To find difference between 2 columns you can use,
1. annotate
2. F expression
Your query would be,
Daily.objects.annotate(diff=F('total_d_sors')-F('missed_d_sors'))
Sample working code with template,
from django.db.models import F
from django.template import Context, Template
context = Context({"daily_objects": Daily.objects.annotate(diff=F('total_d_sors')-F('missed_d_sors'))})
template = Template("{% for i in daily_objects %} {{i.id}} || {{i.diff}}. {% endfor %}")
template.render(context)
I have a content that I'd like to rate on multiple criteria.
Imagine this kind of model:
class Content(models.Model):
name = models.CharField(max_length=50)
class Criterion(models.Model):
name = models.CharField(max_length=50)
content = models.ForeignKey(Content)
class ContRate(models.Model):
user = models.ForeignKey(User, help_text="Who rated ?")
crit = models.ForeignKey(Criterion)
rate = models.DecimalField()
The user has a page displaying the content.
From this page, he can also rate the content on the criteria set
The rating will be done with Ajax.
Now I'm trying to implement the view & the template
view.py
#...
def viewcont(request, content_id):
"""The user can view a content & rate it"""
content = get_object_or_404(Content, pk=content_id)
RateFormSet = modelformset_factory(ContRate)
formset = RateFormSet(queryset=ContRate.objects.filter(content=content, user=request.user))
objs = {
'content': content,
'forms': formset,
}
return render_to_response('content/content_detail.html', objs
, context_instance=RequestContext(request)
)
#...
content_detail.html
<!-- ... -->
<div id="rating">
<ul>
{% for crit in content.crit_set.all %}
<li>
{{ crit }}
<div class="rateit"
data-rateit-value="the_actual_rating_if_already_there"
data-rateit-ispreset="true"
crit-id="{{ crit.id }}"></div>
</li>
{% endfor %}
</ul>
</div>
<!-- ... -->
Now how can I use the forms formset to display the actual rates ?
And how can I draw an empty form to be posted by Ajax from any clicked star ?
(I know the javascript/jQuery part)
Not sure what the point of the formset is here. The rates are all available via the criteria object, using the reverse foreign key to ContRate in exactly the same way as you've done from Criteria to Content.
To make this as efficient as possible, you probably want to get the relevant ratings in the view and bring them together into a single datastructure:
content = get_object_or_404(Content, pk=content_id)
criteria = content.criteria_set.all()
user_ratings = ContRate.objects.filter(content=content, user=request.user)
ratings_dict = dict((c.crit_id, c.rate) for c in user_ratings)
for crit in criteria:
crit.user_rating = ratings_dict.get(crit.id)
Now you can pass criteria directly to your template, and there you can iterate through it to show the user_rating for each one.
(Final point: "criteria" is plural, the singular is "criterion". :-)