I have a model named Assignment in my project
This is how the Assignment model looks like
class Assignment(models.Model):
user = models.ForeignKey(
Teacher, on_delete=models.CASCADE, related_name='assignments')
unique_code = models.CharField(max_length=11, default=assignment_uniqe_id)
title = models.CharField(max_length=250)
deadline = models.DateTimeField()
created_at = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)
subject = models.ForeignKey(
All_Subject, on_delete=models.CASCADE, related_name='assignment_subject')
classes = models.ManyToManyField(Classes)
submitted_by = models.ManyToManyField(Student, blank=True)
description = models.TextField(blank=True)
def __str__(self):
return str(self.user) + " : " + self.title
And I want to check weather if the current date is greater then the deadline.
Please help me out
Related
I have a quiz application made with Django. I am basically loading a pretty complex query. What I am basically doing is creating a new exam with this logic:
Fetch the question from the question bank (the Question model)
I get a certain questions number from each subject and I use them to create a QuestionDraft so I can store and save each student result.
Each QuestionDraft has the AnswerDraft which I use for storing the user answered questions (each AnswerDraft is basically a carbon copy of the question bank Answer).
While I wanna load a 50-question-test everything works pretty fine but when I want to load more than that amount of question, the page is loading extremely slow.
I would like to know if, based on the models and the code I post down below, there is any way to improve the efficiency of the queries and/or the loading time.
models.py
class QuestionSubject(models.Model):
quiz_course = models.ForeignKey(QuizTheoryCourse, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
exam_questions_num = models.IntegerField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Question(models.Model):
id = models.CharField(max_length=7,
default=generate_question_id,
unique=True,
primary_key=True,
editable=False)
question_subject = models.ForeignKey(
QuestionSubject, on_delete=models.CASCADE)
text = models.TextField()
mark = models.IntegerField(default=1)
is_published = models.BooleanField(default=True)
question_bank_id = models.CharField(max_length=255, blank=True, null=True)
question_topic = models.ForeignKey(
QuestionTopic, on_delete=models.CASCADE, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
text = models.TextField()
is_correct = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class QuizProfile(models.Model):
id = models.CharField(max_length=7,
default=generate_question_id,
unique=True,
primary_key=True,
editable=False)
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
subject = models.ForeignKey(
QuestionSubject, on_delete=models.CASCADE, blank=True, null=True)
total_score = models.DecimalField(default=0,
decimal_places=2,
max_digits=5)
quiz_type = models.CharField(
max_length=255, choices=quiz_type, blank=True, null=True)
right_answer = models.IntegerField(default=0)
is_completed = models.BooleanField(default=False)
is_assigned = models.BooleanField(blank=True, null=True, default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.username + ' ' + self.id
class Meta:
ordering = ('-created_at',)
class QuestionDraft(models.Model):
quiz_profile = models.ForeignKey(QuizProfile,
on_delete=models.CASCADE,
blank=True,
null=True)
question = models.ForeignKey(Question,
on_delete=models.CASCADE,
blank=True,
null=True)
text = models.TextField()
is_answered = models.BooleanField(blank=True, null=True)
is_correct = models.BooleanField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.quiz_profile) + ' ' + str(self.question)
class AnswerDraft(models.Model):
quiz_profile = models.ForeignKey(QuizProfile,
on_delete=models.CASCADE,
blank=True,
null=True)
question_draft = models.ForeignKey(QuestionDraft, on_delete=models.CASCADE)
answer = models.ForeignKey(Answer,
on_delete=models.CASCADE,
null=True,
blank=True)
text = models.TextField()
is_answered = models.BooleanField(blank=True, null=True)
is_correct = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.quiz_profile) + ' ' + str(self.answer)
class QuizDraft(models.Model):
id = models.CharField(max_length=7,
default=generate_question_id,
unique=True,
primary_key=True,
editable=False)
quiz_profile = models.ForeignKey(QuizProfile, on_delete=models.CASCADE)
question_draft = models.ForeignKey(QuestionDraft,
on_delete=models.CASCADE,
blank=True,
null=True)
def __str__(self):
return str(self.quiz_profile)
views.py
def ppl_exam_generator_util(request, subjects):
question_list = [Question.objects.filter(question_subject=subject).order_by(
'?')[:int(subject.exam_questions_num)]for subject in subjects]
quiz_profile = QuizProfile(
user=request.user, quiz_type='ppl_exam')
quiz_profile.save()
for ques in question_list:
for q in ques:
question = Question.objects.get(id=q.id)
quiz_attempt = QuizAttempt(quiz_profile=quiz_profile,
question=question)
quiz_attempt.save()
question_draft = QuestionDraft(
question=question, text=question.text, quiz_profile=quiz_profile)
question_draft.save()
quiz_draft = QuizDraft(
quiz_profile=quiz_profile, question_draft=question_draft)
quiz_draft.save()
answers = Answer.objects.filter(question__id=question.id)
shuffle(list(answers))
for ans in answers:
draft_answer = AnswerDraft(
question_draft=question_draft, answer=ans, text=ans.text, quiz_profile=quiz_profile)
draft_answer.save()
return HttpResponseRedirect(reverse('quiz:new_ppl_exam', kwargs={'pk': quiz_profile.id}))
I tried also with the connection.queries tool Django provides, but each query is pretty fast. I don't know if it's a problem with the nested forloop or something else.
Models:
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, default=1,related_name='Employee')
eid = models.IntegerField(primary_key=True)
salary = models.IntegerField(null=True, blank=True)
gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default=1)
contactno = models.CharField(max_length=10, blank=False)
email = models.CharField(max_length=50 ,null=True, blank=True)
country = models.CharField(max_length=30)
address = models.CharField(max_length=60)
def __str__(self):
return self.user.first_name + '_' + self.user.last_name
class Attendance(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1,related_name='Attendance')
attendance_date = models.DateField(null=True)
in_time = models.TimeField(null=True)
out_time = models.TimeField(null=True ,blank=True)
description = models.TextField(null=True, blank=True)
def __str__(self):
return str(self.employee) + '-' + str(self.attendance_date)
class Breaks(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE, default=1)
break_in = models.TimeField(null=True, blank=True)
break_out = models.TimeField(null=True, blank=True)
attendance =models.ForeignKey(Attendance, on_delete=models.CASCADE, default=1,related_name='Breaks')
def __str__(self):
return str(self.employee) + '-' + str(self.break_in) + '-' + str(self.break_out)
def detail_attendance(request):
attendance_list = Attendance.objects.filter(employee__user_id=request.user.id)
counter = Counter()
return render(request, 'employee/detail_attendance.html', {'attendance_list': attendance_list, 'counter': counter})
def detail_break(request):
break_list=Breaks.objects.filter(employee__user_id=request.user.id )
return render(request, 'employee/detail_break.html', {'break_list': break_list})
I have created a function above for detail breaks. I am getting specific user data, but it is giving me the previous data as well. So I need the data for specific date for example in my attendance models I adding attendance of each user.
Please let me know what should I change in detail break.
Use this Queryset:
from django.db.models import Q
from datetime import date
Breaks.objects.filter(
Q(employee__user=request.user) &
Q(attendance__attendance_date=date.today())
)
Or:
Breaks.objects.filter(
Q(employee__user=request.user) &
Q(attendance__attendance_date="2022-11-28")
)
Breaks.objects.filter(date__range=["2011-01-01", "2011-01-31"])
Or if you are just trying to filter month wise:
Breaks.objects.filter(date__year='2011',
date__month='01')
Please reply to this message ,If it doesn't work.
I have three Models, in third models Foreign Key and ManyToMany fields are linked, which are:
Personal_info Models.py
class Personal_info(models.Model):
gen_choices = (
("पुरुष", "पुरूष"),
("महिला", "महिला"),
("तेस्रो", "तेस्रो"),
)
pinfo_id = models.AutoField(primary_key=True)
userid = models.OneToOneField(User, on_delete=models.CASCADE)
nfullname = models.CharField(validators=[max_len_check], max_length=128)
efullname = models.CharField(validators=[max_len_check], max_length=128)
dob_ad = models.DateField()
dob_bs = models.DateField()
gender = models.CharField(max_length=6, choices=gen_choices)
citizen_no = models.CharField(max_length=56)
cissue_dist = models.ForeignKey(District, on_delete=models.CASCADE)
cissue_date = models.DateField()
language = models.CharField(max_length=56)
p_district = models.CharField(max_length=56)
p_vdc = models.CharField(max_length=56)
p_ward = models.CharField(max_length=2)
p_city = models.CharField(max_length=56)
t_district = models.CharField(max_length=56)
t_vdc = models.CharField(max_length=59)
t_ward = models.CharField(max_length=2)
t_city = models.CharField(max_length=56)
telephone = models.BigIntegerField(null=True, blank=True)
mobile = models.BigIntegerField()
mother_name = models.CharField(validators=[max_len_check], max_length=128)
mother_cit = models.CharField(max_length=10, null=True)
father_name = models.CharField(validators=[max_len_check], max_length=128)
father_cit = models.CharField(max_length=10, null=True)
gfather_name = models.CharField(validators=[max_len_check], max_length=128)
gfather_cit = models.CharField(max_length=10, null=True)
spose_name = models.CharField(validators=[max_len_check], max_length=128, null=True)
spose_cit = models.CharField(max_length=10, null=True, blank=True)
image = models.FileField(upload_to="photos/", null=True, blank=True)
cit_image = models.FileField(upload_to="citizens/")
inclu_image = models.FileField(upload_to="inclusions/", null=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.efullname)
Educational Models.py
class Education(models.Model):
edu_id = models.AutoField(primary_key=True)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
institute = models.CharField(max_length=255, validators=[max_len_check])
board = models.CharField(max_length=128, validators=[max_len_check1])
pexam = models.CharField(max_length=16, choices=exam_choices)
faculty = models.CharField(max_length=16, choices=fac_choices)
division = models.CharField(max_length=16, validators=[max_len_check2])
tmarks = models.IntegerField()
percent = models.FloatField(null=True, blank=True)
mainsub = models.CharField(max_length=16, validators=[max_len_check2])
image = models.FileField(upload_to="educations/", null=True, blank=True)
active = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
def __str__(self):
return str(self.userid)
V_applied models.py
class V_applied(models.Model):
appNo = models.IntegerField(null=True, blank=True, default=add_one)
p_srlno = models.IntegerField(blank=True, null=0, default=0)
userid = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Vacancy,on_delete=models.CASCADE)
inclusive = models.ManyToManyField(Inclusive)
bank = models.CharField(max_length=128)
v_no = models.CharField(max_length=32, validators=[max_len_check1])
dep_date = models.DateField()
ser_fee = models.IntegerField()
image = models.FileField(upload_to="vouchers/")
personal_info = models.ForeignKey(Personal_info, on_delete=models.CASCADE, blank=True)
education = models.ManyToManyField(Education, blank=True, default=0)
active = models.BooleanField(default=True)
status = models.CharField(max_length=10, validators=[max_len_check], default="Pending")
remarks = models.CharField(max_length=56, validators=[max_len_check1], default="Pending")
comment = models.CharField(max_length=128, validators=[max_len_check2], blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
#property
def per_info(self):
return (self.personal_info.efullname, self.personal_info.gender, )
'''
def __str__(self):
return str(self.userid) + ':' + str(self.post)
Here I want to make auto save method in CreateView for ForeignKey & ManyToMany fields of V_applied models, for this I tried views.py as below:
#method_decorator(login_required(login_url='login'), name='dispatch')
class v_appliedadd(CreateView):
form_class = V_appliedForm
template_name = 'v_applied/v_applied_form.html'
success_url = '/v_applied/vapp_details/'
def form_valid(self, form):
form.instance.userid = self.request.user
form.instance.personal_info = Personal_info.objects.get(userid=self.request.user)
educationall = Education.objects.filter(userid=self.request.user)
for edu in educationall:
form.instance.education.add(edu)
return super().form_valid(form)
While saving data Error display like this:
ValueError at /v_applied/v_appliedadd/
"<V_applied: testuser>" needs to have a value for field "id" before this many-to-many relationship can be used.
Request Method: POST
Request URL: http://localhost:8000/v_applied/v_appliedadd/
Django Version: 3.0.8
Exception Type: ValueError
Exception Value:
"<V_applied: testuser>" needs to have a value for field "id" before this many-to-many relationship can be used.
Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related_descriptors.py in __init__, line 846
Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python38\python.exe
Python Version: 3.8.1
Python Path:
['D:\\DjangoProject\\app_epf',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38',
'C:\\Users\\User\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\lib\\site-packages']
Server time: Mon, 14 Sep 2020 23:09:21 +0545
I am new in python-django, please help me how to solve it.
form.instance.userid = self.request.user
form.instance.personal_info = Personal_info.objects.get(userid=self.request.user)
instance_from = form.save()
educationall = Education.objects.filter(userid=self.request.user)
for edu in educationall:
instance_edu = Education.objects.get(pk=edu.pk)
instance_from.education.add(instance_edu)
instance_from.save()
return super().form_valid(form)
My group project for school has us building a school management system. I have the following models:
Student:
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
User.is_student = True
enrolled_courses = models.ManyToManyField(Session, blank=True)
def __str__(self):
return f'{self.user.last_name}, {self.user.first_name}'
Session:
class Session(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE)
course_date_start = models.DateTimeField()
course_date_end = models.DateTimeField()
def session_id(self):
new_session_date = self.course_date_start.strftime('%Y')
return f'{new_session_date}{self.course.number}{self.pk}'
def __str__(self):
return f'{self.course.number} - {self.course.title} - {self.session_id()}'
Assignment:
class Assignment(models.Model):
session_link = models.ForeignKey(Session, on_delete=models.CASCADE)
created_date = models.DateTimeField(default=timezone.now)
due_date = models.DateField()
title = models.CharField(max_length=50)
total_points = models.IntegerField()
points_earned = models.IntegerField(blank=True, null=True)
objective = models.TextField()
def __str__(self):
return self.title
The problem right now is if I save one value of points_earned to a user, it saves that value to all, since they're linked by the FK.
What's the best way to handle it so each Student can have their own score for each assignment?
If you want each Student to have their own score for each assignment,then a solution would be to have a table to keep track of the score with those two models as foreign keys.
Use https://docs.djangoproject.com/en/3.1/topics/db/models/#intermediary-manytomany
class StudentAssignment(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
assignment = models.ForeignKey(Assignment, on_delete=models.CASCADE)
points_earned = models.IntegerField(blank=True, null=True)
I runserver to test my Habit Tracker app. Not sure why I get Error in formatting: AttributeError: 'Habit' object has no attribute 'goal'. Have included my models.py. I need your help understanding what I have written incorrectly and how to fix the code. thank you.
class Habit(models.Model):
name = models.CharField(max_length=60)
goal_nbr = models.IntegerField(default=0, null=True, blank=True)
goal_description = models.CharField(max_length=60, null=True, blank=True)
start_date = models.DateField()
end_date = models.DateField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
user = models.ForeignKey(
User, related_name="habit", on_delete=models.CASCADE)
#property
def duration(self):
delta = end_date - start_date
return f'{ delta } days'
def __str__(self):
return f"Your chosen habit is {self.name}, with a goal of {self.goal_nbr} {self.goal._description} for {self.duration} days, from {self.start_date} to {self.end_date}"
class Activity(models.Model):
# name = models.CharField(max_length=60)
result_nbr = models.IntegerField(default=0, null=True, blank=True)
created_at = models.DateField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
user = models.ForeignKey(
User, related_name="activity", on_delete=models.CASCADE)
habit = models.ForeignKey(
'Habit', related_name="activity", on_delete=models.CASCADE)
#property
def diff_between_goal_result(self):
diff_nbr = result_nbr - self.habit.goal_nbr
return f'{ diff_nbr }'
class Meta:
constraints = [models.UniqueConstraint(
fields=['created_at', 'habit'], name='one_update_per_day'), ]
def __str__(self):
return f"Today you achieved: {self.result_nbr} of your {self.habit.name} {self.habit.goal_description}"