Django order by primary key does not work - python

I have a model as below:
class Photos(models.Model):
id = models.IntegerField(primary_key=True, default=1)
name = models.CharField(max_length=500)
size = models.IntegerField()
path = models.CharField(max_length=500)
date = models.DateField(default=datetime.now)
def __str__(self):
return self.date.strftime('%Y-%m-%d')
class Meta:
verbose_name_plural = "Photos"
I want to retrieve the last primary key from the database (postgresql) as below:
try:
last_inserted = Photos.objects.order_by('-id')[0]
print(last_inserted)
except IndexError:
print("No data in the database")
but instead of a primary key I always get a date from the date column which is really strange! printing the last_inserted gives me '2018-09-04'.
As a test I change the 'id' column to lang (does not exists in table) gives below error message:
Cannot resolve keyword 'lang' into field. Choices are: date, id, name, path, size
in the above message why date is coming first then id and so on ..!
please help!

print(last_inserted) will show you result of model's __str__ method. To see id you can change model:
class Photos(models.Model):
id = models.IntegerField(primary_key=True, default=1)
name = models.CharField(max_length=500)
size = models.IntegerField()
path = models.CharField(max_length=500)
date = models.DateField(default=datetime.now)
def __str__(self):
return str(self.id)
class Meta:
verbose_name_plural = "Photos"
Or just change query to select only id field using values_list:
last_inserted = Photos.objects.order_by('-id').values_list('id', flat=True)[0]
print(last_inserted)
As for
in the above message why date is coming first then id and so on ..!
I suppose it because of alphabetical order.

You can also try it like this. A bit shorter
Photos.objects.order_by('-id').first().id
There is also a last()

Related

Django: I am unable to get Django to autocreate an autofield

I am calling BORROWER.objects.create(ssn=Ssn, bname=Name, address=Address, phone=Phone) from views.py to create an entry in my sqlite database. This is my models.py file with the relevant function.
class BORROWER(models.Model):
card_id = models.AutoField(primary_key=True, max_length=7)
ssn = models.CharField(max_length=11)
bname = models.CharField(max_length=71)
address = models.CharField(max_length=79)
phone = models.CharField(max_length=15)
def __str__(self):
return str(self.card_id)
The database entry is successfully created. However, since I am not specifying a value for the card_id field, the value stays as (<django.db.models.fields.AutoField>,) instead of an actual key. When I try to specify a value for card_id it says something about unexpected argument. Am I calling the create function incorrectly?
Edit: The comma is not there in the original code, but I will try with the suggested edits
Remove comma at the end of the card_id and don't use max_length with AutoFiled ..
class BORROWER(models.Model):
card_id = models.AutoField(primary_key=True)
ssn = models.CharField(max_length=11)
bname = models.CharField(max_length=71)
address = models.CharField(max_length=79)
phone = models.CharField(max_length=15)
def __str__(self):
return str(self.card_id)

Extract data from ORM and group by Date

I have a function which data like this :
my_workouts = Workouts.objects.groupby('my_date').filter(
my_date__year=year, my_date__month=month)
I want to do the same with another model where I want to group the weight by date:
Models.py
class Quiz(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quizzes')
scheduled_date = models.DateTimeField(max_length=255, default=0)
weight = models.IntegerField(default=0)
What I tried:
data = Quiz.objects.orderby('scheduled_date').
filter(owner_id=request.user.pk,my_date__year=year, my_date__month=month).
annotate(c=Sum('weight')).values('c')
But this is not working, Please Help!
check your syntax
orderby must be order_by
data = Quiz.objects.order_by('scheduled_date').
filter(owner_id=request.user.pk,my_date__year=year, my_date__month=month).
annotate(c=Sum('weight')).values('c')
refer this

Django Cannot assign "'Pizza'": "Order.Food_Name" must be a "Foods" instance

Hello Guys I am working on a restaurant project which allow user to select food item and book an order but i am getting this error as i try to book an order
"Django Cannot assign "'Pizza'": "Order.Food_Name" must be a "Foods" instance."
I am using drop down menu to select food items i am using django version 2.1.5 . Please Help
views.py
def place_order(request):
name = request.POST["user"]
food_items = request.POST['food_item']
qty = request.POST['qty']
rating = request.POST['ratings']
price = Foods.Food_Price
order = Order(Date=datetime.date, Name_of_Person=name,Food_Name=food_items, Qty=qty, Total=price, Ratings=rating)
order.save()
return render(request, "index.html")
model.py
from django.db import models
class Foods(models.Model):
Food_Number = models.IntegerField(null=False,)
Food_Name = models.CharField(max_length=30, primary_key=True, null=False)
Food_Qty = models.CharField(max_length=10)
Food_Price = models.IntegerField()
def __str__(self):
return f"{self.Food_Number} - {self.Food_Name} {self.Food_Price}"
class Order(models.Model):
Order_id = models.AutoField(null=False, primary_key=True)
Date = models.DateField()
Name_of_Person = models.CharField(null=False, max_length=40)
Food_Name = models.ForeignKey(Foods, on_delete=models.CASCADE)
Qty = models.CharField(max_length=10)
Total = models.IntegerField()
Ratings = models.IntegerField()
def __str__(self):
return f"{self.Order_id} - {self.Name_of_Person} |{self.Food_Name} |{self.Total}"
What can i do solve this error
Problem is in your Order model Food_Name is foreign-key field. So you need to assign model-instance which is Food in this case to this field. But you are assigning food_items = request.POST['food_item'] which is suppose to be food_name string i guess. That is why this error raise. I don't think your model is properly design. Food_Name is not an unique id field in Food model rather in your Order table you would like to have Food not Food_name.

Django: posting to foreign keys results in matching query does not exist

Models:
class CompanyList(models.Model):
company_id = models.CharField(max_length=10, unique=True)
company_name = models.CharField(max_length=100, unique=True)
class Reporting(models.Model):
company = models.ForeignKey(CompanyList, on_delete=models.CASCADE)
year_end = models.DateField()
class CompanyAccountsExtracts(models.Model):
reporting = models.ForeignKey(Reporting, on_delete=models.CASCADE)
data_type = models.CharField(max_length=30)
source = models.CharField(max_length=30)
value = models.CharField(max_length=30)
Now I have a pandas dataframe (company_accounts_extracts_upload) of data to write to CompanyAccountsExtracts. I am using the following code to do so:
for i, row in enumerate(company_accounts_extracts_upload.values):
single_row = company_accounts_extracts_upload.iloc[i].to_dict()
report = models.Reporting.objects.get(company=single_row['Company ID Number'], year_end=single_row['Year End'])
DataExtract = models.CompanyAccountsExtracts(reporting=report,
data_type=single_row['DataType'],
source=single_row['Source'],
value=single_row['Value'],
)
DataExtract.save()
I am getting the following error on the "report = models.Reporting..." line:
DoesNotExist: Reporting matching query does not exist.
However, I'm 100% sure the company and year end does exist as I can see it in the admin view.
I think the error might be related to how I am posting to a foreign key as the Reporting foreign key which again is a foreign key from CompanyList?
You need to update your company query param from:
company=['Company ID Number']
to:
company__company_id=['Company ID Number']
You are getting the error because the company param will need a Company instance and you are only using the company_id field.

how to convert the foreign key to value

I want to query a table with foreign key. Is it possible to replace the foreign key to its value and convert it to dictionary?
Model.py
class Category(models.Model):
name = models.CharField(max_length=40)
class Item(models.Model):
name = models.CharField(max_length=50)
category = models.ForeignKey(Category)
Views.py
dic = {}
dic["data"] = list(Item.objects.all().values())
It is not clear what you are looking for. But I understand that you need a result where instead of ID you get the name of category.
There are two approach. First and better is to change your models as:
class Category(models.Model):
name = models.CharField(max_length=40)
def __str__(self):
return str(self.name)
This is a better method using this you do not have add an extra line requesting name of category each time.
Another is to query in this manner:
Item.objects.all().values('name', 'category__id')

Categories