django models getting queryset - django

how to get status_updation and status_date respect to the order_number
class customer_database(models.Model):
customer_id = models.CharField(max_length=20, unique=True)
customer_name = models.CharField(max_length=20)
customer_email = models.EmailField()
def __str__(self):
return self.customer_id
class order_database(models.Model):
order_number = models.CharField(max_length=10, unique=True, primary_key=True)
order_timestamp = models.DateTimeField()
order_consignment_number = models.CharField(max_length=20)
order_customer = models.ForeignKey(customer_database, on_delete=models.CASCADE)
def __str__(self):
return self.order_number
class track_database(models.Model):
order_status = models.ForeignKey(order_database, on_delete=models.CASCADE)
status_updation = models.CharField(max_length=30)
status_timestamp = models.DateTimeField()
def __str__(self):
return self.status_updation

Try
query_order_number = '1234'
tracker = track_database.objects.filter(order_status.order_number = query_order_number)
print(tracker.status_updation)
print(tracker.status_timestamp)
Let me know if this doesn't work

Or you could go via the order number:
query_order_number = '1234'
order = order_database.objects.filter(order_number = query_order_number)
print(order.track_database.status_updation)
print(order.track_database.status_timestamp)

Related

Django models - how to assign as ForeignKey

My lab has a models.py as below:
class Book(models.Model):
isbn = models.CharField(max_length=10, unique=True)
name = models.CharField(max_length=100)
published_year = models.IntegerField()
total_qty = models.IntegerField()
current_qty = models.IntegerField()
max_duration = models.IntegerField()
author = models.ForeignKey(Author, on_delete=models.PROTECT)
category = models.ForeignKey(Category, on_delete=models.PROTECT)
def __str__(self):
return self.name
class BookCopy(models.Model):
class Status:
AVAILABLE = 1
BORROW =2
LOST = 3
barcode = models.CharField(max_length=30, unique=True)
buy_date = models.DateField(null=True, blank=True)
status = models.IntegerField()
book = models.ForeignKey(Book, on_delete=models.PROTECT)
def __str__(self):
return self.barcode
class User(models.Model):
username = models.CharField(max_length=30, unique=True)
fullname = models.CharField(max_length=100, null=True)
phone = models.CharField(max_length=10, null=True)
def __str__(self):
return self.fullname
class BookBorrow(models.Model):
class Status:
BORROWING = 1
RETURNED = 2
borrow_date = models.DateField()
deadline = models.DateField()
return_date = models.DateField(null=True)
status = models.IntegerField()
book_copy = models.ForeignKey(BookCopy, on_delete=models.PROTECT)
book_name = models.ForeignKey(Book, on_delete=models.PROTECT)
user = models.ForeignKey(User, on_delete=models.PROTECT)
And i wrote the api for borrow_book function like below:
#csrf_exempt
def muon_sach(request):
body = request.POST
username = body.get('username')
barcode = body.get('barcode')
user = User.objects.filter(username=username).first()
bookcopy = BookCopy.objects.filter(barcode = barcode).first()
if not user:
return HttpResponse(json.dumps({
'error':"Nguoi dung khong ton tai"
}))
if not bookcopy:
return HttpResponse(json.dumps({
'error':"ma sach khong ton tai"
}))
book_borrow = BookBorrow()
# resp = []
book_borrow.user = user
book_borrow.book_copy = bookcopy
book_borrow.borrow_date = datetime.now()
book_borrow.deadline = datetime.now() + timedelta(days=bookcopy.book.max_duration)
book_borrow.status = BookBorrow.Status.BORROWING
book_borrow.book_name = bookcopy.book.name
book_borrow.save()
bookcopy.status = BookCopy.Status.BORROW
bookcopy.save()
bookcopy.book.current_qty -=1
bookcopy.book.save()
return HttpResponse(json.dumps({'success':True}))
however when i test with postman (give username and barcode), it gets the error
xxx "BookBorrow.book_name" must be a "Book" instance."
Could you please advise where incorrect and assist me correct it ? Appreciate for any assist
You have to do the following:
#csrf_exempt
def muon_sach(request):
# ... more code here
bookcopy = BookCopy.objects.filter(barcode = barcode).first()
book_borrow.book_name = bookcopy.book
book_borrow.save()
# ... more code here
return HttpResponse(json.dumps({'success':True}))
So in the definition of your model you can see that book_name has the following structure:
class BookBorrow(models.Model):
# ... More code here
book_name = models.ForeignKey(Book, on_delete=models.PROTECT)
user = models.ForeignKey(User, on_delete=models.PROTECT)
It is clear that BookBorrow.book_name must accept a Book instance. So when you pass in you code book_borrow.book_copy = bookcopy it is passing a BookCopy instance so that's the error.
borrow_copy.book is the appropiate.
You have specified book_name to be a Foreign Key to Book, and you try to assign to it the book.name value.
Either you need to set this field as a CharField or you need to rename the field from book_name to book and use book_borrow.book = bookcopy.book

How to get recent values in this db?

I use sqlite.
class Member(models.Model):
member_id = models.AutoField(primary_key=True)
is_update = models.IntegerField(default=0)
member_name = models.CharField(max_length=50)
member_group = models.IntegerField(default=0)
room_name = models.CharField(max_length=20)
bed_name = models.CharField(max_length=20)
gender = models.IntegerField(default=0)
birth_date = models.DateField()
phone_number = models.CharField(max_length=11)
protector = models.CharField(default='protector',max_length=50)
def __str__(self):
return str(self.member_id)
def initIsUpdate(self):
self.is_update = 0
return 0
class Inpatient(models.Model):
member_id = models.ForeignKey(Member, on_delete=models.CASCADE, db_column = 'member_id', related_name='member')
inpatient_status = models.IntegerField(default=0)
is_in_room = models.IntegerField(default=0)
is_on_bed = models.IntegerField(default=0)
heart_rate = models.IntegerField(default=0)
breath_rate = models.IntegerField(default=0)
update_time = models.DateTimeField(auto_now_add=True, blank=True)
protector_name = models.CharField(max_length=50)
def __str__(self):
return str(self.member_id)
And Members are 4 people..
Each Members have same values in Inpatient DB.
It gets new queryset for every 1 sec.
And I want get 4 Member's most recent Inpatient DB.
How I get that DB??
class Inpatient(models.Model):
member_id = models.ForeignKey(Member, on_delete=models.CASCADE, db_column = 'member_id', related_name='member')
inpatient_status = models.IntegerField(default=0)
is_in_room = models.IntegerField(default=0)
is_on_bed = models.IntegerField(default=0)
heart_rate = models.IntegerField(default=0)
breath_rate = models.IntegerField(default=0)
update_time = models.DateTimeField(auto_now_add=True, blank=True)
protector_name = models.CharField(max_length=50)
class Meta:
get_latest_by = "update_time"
def __str__(self):
return str(self.member_id)
Now when you filter the members in views.py it will provide recent values..

How can i make a Query through Many-To-Many-Relationship

I want to display the trainer for a course date. A course can have several dates and a different trainer can be used on each date. A trainer can have a different role on each course date. (Instructor, helper...)
How do I make the correct query? Are the models correct for this?
Models:
class Course_dates(models.Model):
date = models.DateField()
start = models.TimeField()
end = models.TimeField()
def __str__(self):
return str(self.id)
"""return self.date.strftime("%d.%m.%Y")"""
class Course(models.Model):
course_number = models.CharField(max_length=24, blank=True)
course_location = models.ForeignKey(Course_location, on_delete=models.CASCADE)
course_dates = models.ManyToManyField('Course_dates', through="Course_Course_dates")
def __str__(self):
return self.course_number
class Trainer_Course_Course_date_role(models.Model):
trainer = models.ForeignKey(Trainer, on_delete=models.CASCADE)
role = models.CharField(max_length=24, blank=True)
def __str__(self):
return str(self.id)
class Course_Course_dates(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)
course_dates = models.ForeignKey(Course_dates, on_delete=models.CASCADE)
trainer = models.ForeignKey(Trainer_Course_Course_date_role, on_delete=models.CASCADE, null=True)
def __str__(self):
return str(self.id)
class Trainer(models.Model):
salutation = models.CharField(max_length=8,choices=GENDER_CHOICES)
last_names = models.CharField(max_length=56)
first_names = models.CharField(max_length=56)
date_of_birth = models.DateField()
address = models.ForeignKey(Address, on_delete=models.CASCADE)
email = models.EmailField()
phone = models.CharField(max_length=56, blank=True)
mobile = models.CharField(max_length=56, blank=True)
def __str__(self):
return self.last_names
View:
def course(request):
courses = Course.objects.all()
course_list = []
for course in courses:
sorted_date_list = course.course_dates.all().order_by('date')
course_list.append({'course': course, 'sorted_date_list': sorted_date_list })
context = { 'course_list': course_list, }
return render(request, 'kursverwaltung_tenant/course.html', context)

Summing up total amount from multiple models in Django

The title of my question has said it all. I have multiple models, and I want to add up the amount to derive the total amount, here's my code
class FurnitureItem(models.Model):
fur_title = models.CharField(max_length=200)
fur_price = models.FloatField()
fur_discount_price = models.FloatField(blank=True, null=True)
fur_pictures = models.ImageField(upload_to='Pictures/', blank=True)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24)
fur_descriptions = models.TextField()
slug = models.SlugField()
date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.fur_title
class FurnitureOrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
fur_ordered = models.BooleanField(default=False)
item = models.ForeignKey(FurnitureItem, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
def __str__(self):
return f"{self.quantity} of {self.item.fur_title}"
....
def get_final_fur_price(self):
if self.item.fur_discount_price:
return self.get_total_discount_fur_price()
return self.get_total_item_fur_price()
class FurnitureOrder(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
fur_items = models.ManyToManyField(FurnitureOrderItem)
date_created = models.DateTimeField(auto_now_add=True)
ordered_created = models.DateTimeField()
fur_ordered = models.BooleanField(default=False)
def __str__(self):
return self.user.username
def get_total_fur_everything(self):
total = 0
for fur_order_item in self.fur_items.all():
total += fur_order_item.get_final_fur_price()
return total
class GraphicItem(models.Model):
graphic_title = models.CharField(max_length=200)
graphic_price = models.FloatField()
graphic_discount_price = models.FloatField(blank=True, null=True)
graphic_pictures = models.ImageField(upload_to='Pictures/', blank=True)
label = models.CharField(choices=LABEL_CHOICES, max_length=1)
category = models.CharField(choices=CATEGORIES_CHOICES, max_length=24)
graphic_descriptions = models.TextField()
slug = models.SlugField()
date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.graphic_title
class GraphicOrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
graphic_ordered = models.BooleanField(default=False)
item = models.ForeignKey(GraphicItem, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
def __str__(self):
return f"{self.quantity} of {self.item.graphic_title}"
....
def get_final_graphic_price(self):
if self.item.graphic_discount_price:
return self.get_total_discount_graphic_price()
return self.get_total_item_graphic_price()
class GraphicOrder(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
graphic_items = models.ManyToManyField(GraphicOrderItem)
date_created = models.DateTimeField(auto_now_add=True)
ordered_created = models.DateTimeField()
graphic_ordered = models.BooleanField(default=False)
def __str__(self):
return self.user.username
def get_total_graphic_everything(self):
total = 0
for graphic_order_item in self.graphic_items.all():
total += graphic_order_item.get_final_graphic_price()
return total
what i've tried as regards summing up the amount for furniture and graphics
class TotalAmount(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
graphic_items = models.ManyToManyField(GraphicOrderItem)
fur_items = models.ManyToManyField(FurnitureOrderItem)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
def amount(self):
return self.graphic_items.get_total_graphic_everything() + self.fur_items.get_total_fur_everything()
Then my views goes this way:
class Summary(LoginRequiredMixin, View):
def get(self, *args, **kwargs):
try:
fur_order = FurnitureOrder.objects.get(user=self.request.user, fur_ordered=False)
graphic_order = GraphicOrder.objects.get(user=self.request.user, graphic_ordered=False)
amount = TotalAmount.objects.get(user=self.request.user)
context = {
'fur_order':fur_order,'graphic_order':graphic_order,'amount':amount}
return render(self.request, 'business/home-order-summary.html', context)
Thanks for your time, I no the code is lengthy, but I wanted to expanciate better.

Get Foreign Key Value

How can I get the foreign key values? I have a common vehicle model that links to the year, series, engine type, body style, transmission and drive train...all as foreign keys. I'd like to get the values of these fields for my app, but I'm stuck as to how I'd go about them. Any ideas will be highly appreciated.
class Model(models.Model):
model = models.CharField(max_length=15, blank=False)
manufacturer = models.ForeignKey(Manufacturer)
date_added = models.DateField()
def __unicode__(self):
name = ''+str(self.manufacturer)+" "+str(self.model)
return name
class Year(models.Model):
ALPHA_NUMERIC_CHOICES = (
('1', 'Numeric'),
('A', 'Alphabetic'),
)
year = models.PositiveSmallIntegerField()
position_7_char = models.CharField(max_length=1, choices=ALPHA_NUMERIC_CHOICES)
position_10 = models.CharField(max_length=1, blank=False)
def __unicode__(self):
return unicode(self.year)
class Series(models.Model):
series = models.CharField(max_length=20, blank=True)
model = models.ForeignKey(Model)
date_added = models.DateField()
def __unicode__(self):
name = str(self.model)+" "+str(self.series)
return name
class CommonVehicle(models.Model):
year = models.ForeignKey(Year)
series = models.ForeignKey(Series)
engine = models.ForeignKey(Engine)
body_style = models.ForeignKey(BodyStyle)
transmission = models.ForeignKey(Transmission)
drive_train = models.ForeignKey(DriveTrain)
def __unicode__(self):
name = ''+str(self.year)+" "+str(self.series)
return name
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6, blank=False)
vin = models.CharField(max_length=17, blank=False)
common_vehicle = models.ForeignKey(CommonVehicle)
exterior_colour = models.ForeignKey(ExteriorColour)
interior_colour = models.ForeignKey(InteriorColour)
interior_type = models.ForeignKey(InteriorType)
odometer_unit = models.ForeignKey(OdometerUnit)
status = models.ForeignKey(Status)
odometer_reading = models.PositiveIntegerField()
selling_price = models.PositiveIntegerField()
purchase_date = models.DateField()
sales_description = models.CharField(max_length=60, blank=False)
def __unicode__(self):
return self.stock_numberodels.ForeignKey(CommonVehicle)
You need the actual IDs? Try something like my_vehicle_ref.series.id.
Also, I hope you know that the series attribute right there is really an instance of Series, so you could access any of it's properties, e.g., my_vehicle_ref.series.model.model.