I'm new in django. I want to create a table that includes some fields calculated from other model's field.
class Student(models.Model):
name = models.Charfield(max_length = 30)
...
class Subject(models.Model):
student = models.ForeignKey(Student, related_name = "student_subject")
point = models.IntegerField(default = 0)
...
How can I create a queryset to get average point for each student?
The relevant documentation is: https://docs.djangoproject.com/en/1.11/topics/db/aggregation/
from django.db.models import Avg
students = Student.objects.annotate(Avg('subject__point'))
Related
My model looks like this.
class Student(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
roll_no = models.CharField(max_length=32)
course = models.CharField(max_length=120)
Now I want to make a filter form using django_filters and want to use distinct values of course field as choices of select input but it requires each value to be associated with unique id and this field doesn't have any unique id.
I tried this:
class StudentFilter(django_filters.FilterSet):
course = django_filters.ModelChoiceFilter(queryset=Student.objects.values("course",flat = True).distinct(),empty_label=('Course'))
class Meta:
model = Student
fields = []
but it didn't work.
Note I do not want to make separate model for course.
The AllValuesFilter does exactly what you are asking for I believe
class StudentFilter(django_filters.FilterSet):
course = django_filters.AllValuesFilter(field_name="course")
class Meta:
model = Student
fields = []
model.py
class LabTable(models.Model):
LabNo = models.AutoField(primary_key=True)
Pid = models.IntegerField()
Weight = models.IntegerField()
DoctorId = models.ForeignKey(DoctorTable,on_delete=models.CASCADE)
Date = models.DateField()
Category = models.CharField(max_length=50)
PatientType = models.CharField(max_length=50)
Amount = models.IntegerField()
class DoctorTable(models.Model):
DoctorId = models.AtuoField(primary_key = True)
DoctorName = models.CharField(max_length = 50)
Department = models.CharField(max_length = 100)
1.Here, I have created the lab model and a foreign key with doctor table. I want to use doctor table to present data in dropdown.
You can specify how to show a DoctorTable model object by implementing the __str__ method for that model, so:
class DoctorTable(models.Model):
DoctorId = models.AutoField(primary_key=True)
DoctorName = models.CharField(max_length=50)
Department = models.CharField(max_length=100)
def __str__(self):
return self.DoctorName
Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: doctor_name instead of DoctorName.
Note: Models normally have no Table suffix. A model is not a table, it is stored in a relational database as a table, but even then it has extra logic like validators, managers, etc.
CHOICES = (('Earned Leave','Earned Leave'),('Casual Leave','Casual Leave'),('Sick Leave','Sick Leave'),('Paid Leave','Paid Leave'))
STATUS_CHOICES = (('0', 'Rejected'),('1', 'Accepted'),)
class Leave(models.Model):
employee_ID = models.CharField(max_length = 20)
name = models.CharField(max_length = 50)
user = models.ForeignKey(User, on_delete = models.CASCADE, null =True)
type_of_leave = models.CharField(max_length = 15, choices = CHOICES)
from_date = models.DateField()
to_date = models.DateField()
status = models.CharField(max_length = 15, choices = STATUS_CHOICES)
class History(models.Model):
name = models.CharField(max_length = 50)
employee_ID = models.CharField(max_length = 20)
earned_leave = models.IntegerField()
casual_leave = models.IntegerField()
sick_leave = models.IntegerField()
paid_leave =models.IntegerField()
def __str__(self):
return self.name
I want to store the values name and employee_ID from model Leave into the model History only after the status == 1. I'm pretty new to django, help me with this.
If you want to relate a model to another model then based on relation you can use OneToOneField, ManyToManyField, ForeignKey, etc
Here what you have done is that you have a model Leave with Fields employee_ID, name and user
Another model History with fields employee_ID, name, user (inherited from Leave) and emp_ID, full_name. This is just extending that model class and creating new model objects. Both will remain unrelated only. (I don't have enough experience to tell you exact/detailed behaviour)
So, for you case you can have a OneToOneField(or something else based on your business logic) from history model to leave model something like this.
class Leave(models.Model):
employee_ID = models.CharField(max_length = 20)
name = models.CharField(max_length = 50)
user = models.ForeignKey(User, on_delete = models.CASCADE, null =True)
class History(models.Model):
emp_ID = models.CharField(('employee ID'),max_length = 25)
full_name = models.CharField(('Name'),max_length = 40)
leave = models.OneToOneField(Leave, on_delete = models.SET_NULL)
Then you can save your data as follows :
# I am assuming you're inside some view and you want to create leave for the user who is logged in, refactor based on your requirements
leave = Leave.objects.create(employee_ID="EMPLOYEEID", name="EMPLOYEENAME", user=request.user)
# here pass the leave that we have created previously
history = History.objects.create(emp_ID="EMPLOYEEID", full_name="EMPLOYEEFULLNAME", leave=leave)
I am assuming you're having leave start and end datetime field also. I think you should also look into why employee ID is repeated in both models.
Let me know if you have any doubts/queires. Thanks~
I'm using django-tables-2 for a project. I have a table that uses a model for displaying data but I need to add one more column to display some informations from another table. Can I do that?
Have you tried the following?
# models.py
class Person(models.Model):
" This is your regular model "
first_name = models.CharField(max_length=200)
last_name = models.CharField(max_length=200)
user = models.ForeignKey("auth.User")
dob = models.DateField()
class PersonTable(tables.Table):
id = tables.Column(name="id") # just add a field here
class Meta:
model = Person
You map the column either by having the same name of the model's attribute, either using the accessor property.
I guess in your case it would be:
class UsersTable(tables.Table):
custom = Column(_("Custom"), accessor='id', orderable=False) # Any attr will do, dont mind it
def render_custom(self, record):
return services.get_some_info(record)
class Meta:
model = User
fields = (b'username', )
I have django model
class TestResult(models.Model):
chemical_name = char(50)
value =char(50)
unit = choices(UNIT_CHOICES)
method = choices(METHOD_CHOICES)
CSUSNormal = char(50)
CSUSCaution = char(50)
In admin page this model consist of 180 records. Now i want to apply ordering for these records by creating field order_num. how can i set the ordering based on the order_num of each field?
I admin page i want to see all the records based on the order_num field. How can i achieve this?
Meta.ordering
class TestResult(models.Model):
chemical_name = models.CharField(max_length=50)
value =models.CharField(max_length=50)
unit = models.CharField(choices=UNIT_CHOICES)
method = models.CharField(METHOD_CHOICES)
CSUSNormal = models.CharField(max_length=50)
CSUSCaution = models.CharField(max_length=50)
order_num=models.IntegerField()
class Meta:
ordering=" order_num"