I have a task:
To make a database model with essentially 'student' and 'group'.
'Student' contains: 'Name', 'student ID card', 'group' (must be ForeigKey to Group!)
'Group' contains: 'group name' and 'captain' (must be foreign key to Student!)
Now I have a collision - right straight it's impossible. So I did it in this way:
class Group(models.Model):
group_name = models.CharField(max_length=50)
class Student(models.Model):
name = models.CharField(max_length=50)
birth_date = models.DateField()
std_ID_card = models.IntegerField()
group = models.ForeignKey(Group)
class Captain(models.Model):
student = models.OneToOneField(Student)
group = models.OneToOneField(Group)
Do I have more elegant and correct way to do this?
Try to add a related_name:
class Student(models.Model):
name = models.CharField(max_length=50)
birth_date = models.DateField()
std_ID_card = models.IntegerField()
group = models.ForeignKey('Group')
class Group(models.Model):
group_name = models.CharField(max_length=50)
captain = models.ForeignKey('Student', related_name='%(class)s_captain')
Why is the original structure impossible?
class Group(models.Model):
group_name = models.CharField(max_length=50)
captain = models.ForeignKey('Student')
class Student(models.Model):
name = models.CharField(max_length=50)
birth_date = models.DateField()
std_ID_card = models.IntegerField()
group = models.ForeignKey(Group)
Related
Struggling with Django query, need some help.
So I would like to get data for 5 different variables, accounts_data = (only username), user_account_data = (name), country_data = (iso_code), category_data = (choice), permisisons_data = (permissions).
All data of the models is connected with UserAccount table, so need to get data from other tables only for existing user_accounts
Example of models:
class Account(models.Model):
username = models.CharField(max_length=30)
password = models.CharField(max_length=50)
status = models.CharField(max_length=60)
class UserAccount(models.Model):
name= models.CharField(max_length=100)
surname = models.CharField(max_length=100)
category= models.ManyToManyField(Category)
account = models.ForeignKey(Account)
country = models.ForeignKey(Country)
permissions = models.ForeignKey(Permissions)
class Country(models.Model):
iso_code = models.CharField(max_length=6)
zip_code = models.CharField(max_length=10)
class Category(models.Model):
choice = models.CharField(max_length=12)
connected_category = models.CharField(max_length=12)
class Permissions(models.Model):
permission = models.CharField(max_length=50)
restriction = models.CharField(max_length=30)
I am following the example in the documentation: https://docs.djangoproject.com/en/3.2/topics/db/models/#extra-fields-on-many-to-many-relationships
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
def __str__(self):
return self.name
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
In this case, given a Person object, how can I access all the groups that Person is in?
You access these with:
Group.objects.filter(members=my_person_object)
Okay so I don't know how to frame this.
I have two models Employee and Customer. I am storing the Employee as foreign key in Customer model under emp_id. The epm_id stores the primary key of the employee who admits the customer. I am not sure how to do this in django.
Here are my models:
class Customer(models.Model):
firstname = models.CharField(max_length=15)
lastname = models.CharField(max_length=15)
age = models.IntegerField()
sex = models.CharField(max_length=10)
phoneno = models.IntegerField()
emailid = models.CharField(max_length=25)
address = models.CharField(max_length=50)
children = models.IntegerField()
adults = models.IntegerField()
roomtype = models.CharField(max_length=10)
aadharno = models.CharField(max_length=15)
daysstayed = models.IntegerField()
date_visited = models.DateTimeField(default=timezone.now)
emp_id = models.ForeignKey(Employee,on_delete=models.SET_NULL,blank=True,null=True)
class Employee(models.Model):
firstname = models.CharField(max_length=15)
lastname = models.CharField(max_length=15)
age = models.IntegerField()
sex = models.CharField(max_length=10)
phoneno = models.IntegerField()
emailid = models.CharField(max_length=25)
address = models.CharField(max_length=50)
salary = models.IntegerField()
designation = models.CharField(max_length=10)
password = models.CharField(max_length=10)
aadharno = models.CharField(max_length=15)
datejoined = models.DateField(default=timezone.now)
I need some help here.
The best way I could suggest is that you create the models as follows:
models.py
from django.db import models
from django.contrib.auth.models import User
SEX = [
('male', 'Male'),
('female', 'Female'),
('not_to_say', 'Rather not to say')
]
class BaseModel(models.Model):
age = models.IntegerField()
sex = models.CharField(max_length=20, choices=SEX)
phone = models.CharField(max_length=10)
address = models.CharField(max_length=50)
aadhar_no = models.CharField(max_length=15)
class Employee(BaseModel):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='employee_user')
salary = models.IntegerField()
designation = models.CharField(max_length=10)
class Customer(BaseModel):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='customer_user')
childrens = models.IntegerField()
adults = models.IntegerField()
room_type = models.CharField(max_length=10)
days_stayed = models.IntegerField()
date_visited = models.DateTimeField(default=timezone.now)
employee = models.ForeignKey(Employee, on_delete=models.SET_NULL, relted_name='serving_employee')
You can access password, date_joined, first_name, last_name & email of employee from Employee.user, and first_name, last_name & email of customer from Customer.user.
I hope this solves your problem.
I need a query to retrieve the name and id of the 4 model classes (P, B, M, C, Pt) with a concat.
The class Pt has the foreign key to the parents class by the id
The expected result should be like this: Pt.name, Product.num , concat(B.name, M.name, V.name)
I try several approaches and the more similar it's this one
Models:
class B(models.Model):
b_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
class M(models.Model):
m_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
class V(models.Model):
v_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
class Pt(models.Model):
pt_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
class Product(models.Model):
p_id = models.AutoField(primary_key=True)
p_ref_fk = models.DecimalField(max_digits=5, decimal_places=2, null=True)
pt_fk = models.ForeignKey(Pt, on_delete=models.CASCADE)
b_fk = models.ForeignKey(B, on_delete=models.CASCADE)
m_fk = models.ForeignKey(M, on_delete=models.CASCADE)
v_fk = models.ForeignKey(V, on_delete=models.CASCADE)
Query:
# Get all the P related
p = Product.objects.all().filter(pt_fk__pt_id=1116).filter(b_fk__b_id=3).filter(m_fk__m_id=53).filter(v_fk__v_id=352)
# check the query
print(p.query)
# get the results
print(p)
As per i get your question, you need to Concat foreignkey with - Pt.name, Product.num , concat(B.name, M.name, V.name)
queryset = Employee.objects.annotate(fullname=Concat('first_name', 'last_name'))
this is my own example please change as per your requirements
try this too
class Students(models.Model):
id = models.BigAutoField(primary_key=True)
admission_no = models.CharField(max_length=255)
roll_no = models.CharField(unique=True, max_length=50, blank=True, null=True)
academic_id = models.BigIntegerField()
course_parent_id = models.BigIntegerField()
course_id = models.BigIntegerField()
first_name = models.CharField(max_length=20)
middle_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
user_id = models.BigIntegerField()
date_of_birth = models.DateField(blank=True, null=True)
date_of_join = models.DateField(blank=True, null=True)
class Courses(models.Model):
id = models.BigAutoField(primary_key=True)
parent_id = models.IntegerField()
course_title = models.CharField(max_length=50)
slug = models.CharField(unique=True, max_length=50)
tenant_user = models.ForeignKey('Users', models.DO_NOTHING, default='')
course_code = models.CharField(max_length=20)
course_dueration = models.IntegerField()
grade_system = models.CharField(max_length=10)
is_having_semister = models.IntegerField()
is_having_elective_subjects = models.IntegerField()
description = models.TextField()
status = models.CharField(max_length=8)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = True
db_table = 'courses'
def __unicode__(self):
return self.course_title
class StudentProfileSerializer(ModelSerializer):
class Meta:
model = Students
depth = 0
fields = '__all__'
The first two tables/class contains the course and student table and the third contains the serializer. Can anyone please help how to query using the joins in django. I need to fetch the course_title from Courses table and first_name from Students table.
IMHO, you should review your models; course_id in Students should be a course=models.ForeignKey('Courses', ...); this way you can refer to the course title using dot notation;
student=Student.objects.filter(pk=...)
to refer to your required fields:
student.last_name, student.course.course_title
Besides, if I understood your models, you could get some incongruence... what if the value stored in course_parent_id in Students model is different from the value stored in parent_id in Courses model? maybe the first one is redundant.
To query a field from a related object use a double underscore. So you could do
Student.objects.filter(**kwargs).values('first_name', 'last_name', 'course__course_name')