Django models - how to assign as ForeignKey - django

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

Related

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)

How can I deal with filter object in HTML

I tried with above to see how I can use with objects in showing in homepage.
few people recommend me to use this code below
infos = Info.objects.select_related('user','group', 'user_number').filter(id = newc.id)
and my model code is like this.
class Group(models.Model):
name = models.CharField(max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Type(models.Model) :
name = models.CharField(max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Info(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField(null=True, blank=True, unique=True)
memo = models.CharField(max_length=200, null=True)
birthday = models.CharField(max_length=12,null=True, blank=True)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
regdt = models.DateTimeField(auto_now_add=True)
updatedt = models.DateTimeField(auto_now_add=True)
class Number(models.Model):
number = models.CharField(max_length=11)
info = models.ForeignKey(Info, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
type = models.ForeignKey(Type, on_delete=models.CASCADE)
regdt = models.DateTimeField(auto_now_add=True)
updatedt = models.DateTimeField(auto_now_add=True)
and in my views.py.
def addcontract(request) :
if request.user.is_authenticated :
pk = request.user.id
name = request.POST['name']
email = request.POST['email']
memo = request.POST['memo']
birthday = request.POST['birthday']
group_id = request.POST['group_id']
type_id = request.POST['type_id']
number = request.POST['number']
user_id = pk
newc = Info(
name = name, email = email, memo = memo, birthday = birthday,
group_id = group_id, user_id = pk)
newc.save()
number = Number(number = number, type_id= type_id, user_id = pk, info = newc)
number.save()
infos = Info.objects.select_related('user','group', 'user_number').filter(id = newc.id)
grouplist = Group.objects.filter(user_id = request.user.id)
typelist = Type.objects.filter(user_id = request.user.id)
return render(request, 'detail.html',
{'infos':infos, 'grouplist':grouplist, 'typelist':typelist})
My previous question was
How to connect all related DB with FK in Django?
it doesn't work in homepage at all to show from object that's why I tried to check in homepage then problem occured.
user_id is only for account. I need to use Info_id as a fk all in query
please help this.

Modify database in django

I am a beginner in django. Following is my Attendance Management App.
This is my models.py.
from django.db import models
class Subject(models.Model):
subject_name = models.CharField(max_length=20)
#attendance = models.ForeignKey(Attendance, on_delete =
models.DO_NOTHING)
attendance = models.IntegerField(default=0)
def __str__(self):
return self.subject_name
class Section(models.Model):
section_name = models.CharField(max_length=20)
subject = models.ManyToManyField(Subject)
def __str__(self):
return self.section_name
class Student(models.Model):
rollno = models.IntegerField()
name = models.CharField(max_length=20)
section = models.ForeignKey(Section, on_delete = models.DO_NOTHING,
default=0)
def __str__(self):
return str(self.rollno) + self.name
class Teacher(models.Model):
#teacher_name = models.CharField(max_length=20)
section = models.ForeignKey(Section, on_delete=models.CASCADE)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
#section_name = models.CharField(max_length=10)
#subject_name = models.CharField(max_length=30)
def __str__(self):
return self.section.section_name+' '+self.subject.subject_name
class TeacherList(models.Model):
teacher_name = models.CharField(max_length=20)
teacher = models.ManyToManyField(Teacher)
def __str__(self):
return self.teacher_name
The line below is not working in views.py
student = models.Student.objects.get(rollno = sroll)
student.section.subject.get(subject_name = 'java').attendance += 1
student.save()
This view is called from a template when a button is clicked to add attendance of a student.
The attendance in above code is not modified. Please help me out.
You're saving the student, instead of the subject.
student = models.Student.objects.get(rollno = sroll)
subject = student.section.subject.get(subject_name='java')
subject.attendance += 1
subject.save()
Or, better, do the update directly in one go:
student.section.subject.filter(subject_name='java').update(attendance=F('attendance')+1)
and there's no need to save at all.

django models getting queryset

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)

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.