How to append queried objects from Django database? - python

I have a model with 2 fields for numbers. I am trying to query those numbers and append them to each others. How do I do that? How do I work with queried objects?
This is Model
class Post(models.Model):
title = models.CharField(max_length=100)
num1 = models.IntegerField(blank=True,default=0)
num2 = models.IntegerField(blank=True,default=0)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('diary:post-detail', kwargs={'pk': self.pk})
This is view (here I am trying to query and work with queried objects)
def home(request):
a = Post.objects.values('num1')
b = Post.objects.values('num2')
result = a + b
context = {
'result': result,
}
return render(request, 'diary/home.html', context)
This is a working part of my template
{% for x in result %}
<p> {{ x }} </p>
{% endfor %}
This is the error I get
TypeError at /
unsupported operand type(s) for +: 'QuerySet' and 'QuerySet'
C:\Users\detal\Coding\Trading Diary3\TradingDiary\diary\views.py, line 11, in home
result = a + b

The return of your query will be dictionary. To add both query's you can try
result = q.union(b)
for a much more cleaner look
records = query1 | query2
If you don't want duplicates, then add .distinct()
records = (query1 | query2).distinct()
if you want specific field only you can try
Post.objects.all().values_list(
"num2").union(Post1.objects.all().values_list("num1"))
or if it is from same table
Post1.objects.all().values_list("num1","num2"))

I solved it. Here's my view code:
def home(request):
x = Post.objects.all().values_list("num1","num2")
array = []
for i in x:
y = i[0] + i[1]
array.append(y)
context = {
'posts': Post.objects.all(),
'array':array,
}
return render(request, 'diary/home.html', context)
and template code:
{% for i in array %}
<p> {{ i }} </p>
{% endfor %}
The output is the list of appended numbers of num1 and num2. There was also problem for me while solving - you don't need to "return" the for loop result in views. It works only without it

Related

How to format date and time in Django?

I am trying to record the creation time, date of input data into a SQLite in Django in the format Jan 1, 2021, 8:21 a.m.. So far I can get the time to work doing the following in models.py:
class Listing(models.Model):
time = models.TimeField(auto_now_add=True)
date = models.DateField()
def __str__(self):
return f"({ ({self.time}))"
with my html:
{% block body %}
<div>
<p> Started: {{listing.date}},{{listing.time}}</p>
</div>
{% endblock %}
My views.py [note I've removed some additional that does not have to do with this question]:
def listing(request, name):
listing = Listina.objects.get(listingTitle=name)
return render(request, "auctions/listing.html", {
"listing": listing,
})
I get the following error:
Exception Type: OperationalError at /
Exception Value: no such column: auctions_listing.date
So I'm assuming it's because date in Listing is null. How can I fix this?
I just made the field to null = true:
class Listing(models.Model):
time = models.TimeField(auto_now_add=True)
date = models.DateField(null = true)
def __str__(self):
return f"({ ({self.time}))"
Then ran makemigrations and migrate

How to return entire table row in array by foreign key and how to access from template in django models

I have tried like this. But it is returning the only one combined value.
class Employees(models.Model):
nameininitials = models.TextField(null=True)
nameinuse = models.TextField(null=True)
employeeno = models.TextField(null=True)
departmentname = models.TextField(null=True)
def __str__(self):
return '{} {}'.format(self.nameinuse, self.employeeno)
class Region(models.Model):
regionname = models.TextField(null=True)
regionalincharge = models.ForeignKey(Employees, on_delete=models.CASCADE,null = True)
When I use datalist = Region.objects.all() , I want all fields from Employees table in different variables or array to use in template.
# If this is your query in your views function or class
datalist = Region.objects.all()
# then you can access 'Employees' data in your template by using '.' operator.
For example
views.py
def view_function(request):
datalist = Region.objects.all()
return render(request, 'template_name.html', { 'datalist': datalist })
template_name.html
{% for data in datalist %}
<p>{{data.regionalincharge.nameininitials}}</p>
<p>{{data.regionalincharge.nameinuse}}</p>
<p>{{data.regionalincharge.employeeno}}</p>
<p>{{data.regionalincharge.departmentname}}</p>
<hr />
{% endfor %}

Django model FloatField error 'float' object has no attribute 'as_tuple'

I have a Django model with a FloatField, which I later base a form on. For some reason I get "'float' object has no attribute 'as_tuple'", and unfortunately I have no idea why do I get this error or how to fix it.
models.py:
class Course(models.Model):
title = models.CharField(max_length = 200)
author = models.ForeignKey(User,default=None, on_delete=models.SET_DEFAULT)
description = models.TextField(max_length=1000, blank=True)
tags = models.TextField(blank = True)
duration = models.FloatField(validators=(MinValueValidator(0.1),MaxValueValidator(12), DecimalValidator(max_digits=3,decimal_places=2)))
def __str__(self):
return self.title
forms.py:
class CourseForm(ModelForm):
class Meta:
model = Course
fields = ('title', 'description', 'price', 'duration', 'tags')
views.py:
#login_required
def create_course(request):
if request.method == "POST":
form = CourseForm(request.POST)
if form.is_valid():
form.save()
messages.info(request, f"Course created succesfully!")
else:
messages.error(request, "Something went wrong, please resubmit!")
form = CourseForm()
return render(request, "main/createcourse.html", {"form": form})
html:
{% extends 'main/header.html' %}
<body>
{% block content%}
<div class="container">
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<br>
<button class="btn" type="submit">Create</button>
</form>
If you to modify an existing course, click <strong>here</strong> instead.
</div>
<br><br>
{% endblock %}
</body>
If you really need to use a FloatField, then you need to write your own validator:
def validate_decimals(value):
s = str(value)
d = decimal.Decimal(s)
if abs(d.as_tuple().exponent) > 2:
raise ValidationError(
_('%(value)s has more than 2 decimals. Please enter 2 decimals only.'),
params={'value': value},
)
Then, you add validators='validate_decimals' when you declare the FloatField.
Note that a float value cannot directly be converted to decimal. It should first be converted to string and then to decimal. See also:
Python float to Decimal conversion
There is a difference between a float and a Decimal. A Decimal encodes the data by storing the digits of a decimal number. You can however not perform DecimalValidation on a float, since due to rounding errors, it will add extra digits.
You thus can use a DecimalField [Django-doc] instead. Note that you thus need to pass Decimal objects in that case, not floats.
class Course(models.Model):
title = models.CharField(max_length = 200)
author = models.ForeignKey(User,default=None, on_delete=models.SET_DEFAULT)
description = models.TextField(max_length=1000, blank=True)
tags = models.TextField(blank = True)
duration = models.DecimalField(max_digits=3,decimal_places=2, validators=(MinValueValidator(0.1),MaxValueValidator(12), DecimalValidator(max_digits=3,decimal_places=2)))
def __str__(self):
return self.title
You might want to take a look at the DurationField [Django-doc] to store duration however, this will automatically use a timedelta, and store it as an integer for databases that do not support such types.

Django displaying data from database in template

I'm having some trouble displaying data from my database on the template in django
model:
class CityInfo (models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
landmark_type = models.CharField(blank=True, max_length=30)
business = 'Business'
student = 'Student'
tourist = 'Tourist'
def __str__(self):
return self.name
relevant view:
def itemget(request):
data=CityInfo.objects.all()
return render(request,'CityApp/infopage.html', {'data': data})
relevant url:
url(r'itemget/$',views.itemget,{'template_name': 'CityApp/info_page.html'},name='itemget'),
infopage.html:
<ul>
{% for item in data %}
<li>
<h1>{{ item.name }}</h1>
</li>
{% endfor %}
<ul>
The above html results in a blank list and I have no idea why.
Try changing views.py to the following:
def itemget(request):
data = CityInfo.objects.all()
context={
'data': data
}
return render(request, "CityApp/infopage.html", context)
Try this :
def __str__(self):
return "%s" % self.name
I'm not sure because I'm on my old smartphone.
Otherwise, your def __str__ is well indented in your class ?
Are you using Python 2 or Python 3 ? str if for Python 3. Else you have to use __unicode__
EDIT :
From you urls.py file, you have :
url(r'itemget/$',views.itemget,{'template_name': 'CityApp/info_page.html'},name='itemget'),
Remove your template_name part which is already in your view and don't forget to add ^ before itemget
url(r'^itemget/$',views.itemget ,name='itemget'),

QuerySet Returns Empty List Instead of error

I think my queryset is returning an empty list instead of a "Does not exist error". I want it to return an error so that I can return an alternative message. The HTML is returning an empty bullet point instead of the desired message.
view.py
def results(request, foo_id):
template_name = 'results.html'
foo = Foo.objects.get(id=foo_id)
foo_id = foo_id
try:
foobars = FooBar.objects.filter(foo__foo=foo.foo)
return render(request, template_name, {'foobars': foobars,
'zipcode':zipcode, 'foo_id':foo_id})
except FooBar.DoesNotExist:
message = 'Sorry there are no FooBar with that foo'
return render(request, template_name, {'message':message,
'foo_id':foo_id})
models.py
class Foo(models.Model):
foo = models.IntegerField(null=True)
class FooBar(models.Model):
foo = models.ForeignKey('Foo')
title = models.CharField(max_length=100)
description = models.CharField(max_length=400, null=False, blank=True )
def __str__(self):
return self.title
results.html
<html>
<h2>Title</h2>
<ul id='id_results'>
{% for foobar in foobars%}
<li>{{ foobar.name }}</li>
{% empty %}
<li> {{ message }} </li>
{% endfor %}
</ul>
New FooBar
.filter() does not raise an exception if objects does not exist in the queryset, it returns an empty list [] instead.
We could have used a .get() on the queryset which raises this exception in case no objects exist. But, we won't be able to use it as there might be multiple objects in the queryset matching the criteria and in case of multiple objects being returned, it raises an exception.
get() raises MultipleObjectsReturned if more than one object was
found.
You can instead check using the booleanness of foobars and in case of it being an empty list, display the message.
def results(request, foo_id):
template_name = 'results.html'
foo = Foo.objects.get(id=foo_id)
foo_id = foo_id
foobars = FooBar.objects.filter(foo__foo=foo.foo)
if foobars: # check if there are any matching objects
return render(request, template_name, {'foobars': foobars,
'zipcode':zipcode, 'foo_id':foo_id})
else: # no matching objects
message = 'Sorry there are no FooBar with that foo' # display the message
return render(request, template_name, {'message':message,
'foo_id':foo_id})

Categories

Resources