Need help in adding Foreign key using django models - python

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.

Related

how to store user data from user model inside a database table in django

I have a Buyer table in mysql database and I want to take the username , email, password from User model ( default django model ) and store it inside Buyer table,
Buyer model in models.py:
class Buyer(models.Model):
row_id = models.AutoField(primary_key=True)
user_name = models.CharField(unique=True, max_length=50)
user_password = models.CharField(max_length=16)
first_name = models.CharField(max_length=50)
middle_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50)
email = models.CharField(unique=True, max_length=100)
home_phone = models.CharField(max_length=20, blank=True, null=True)
mobile_phone = models.CharField(unique=True, max_length=20)
personal_id = models.CharField(max_length=30, blank=True, null=True)
idtype_fk = models.ForeignKey('Idtype', models.DO_NOTHING, db_column='idType_FK', blank=True, null=True) # Field name made lowercase.
personal_id_country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='personal_id_country_FK',related_name='personal_id_country_fk') # Field name made lowercase.
address_line_1 = models.CharField(db_column='address_Line_1', max_length=200) # Field name made lowercase.
address_line_2 = models.CharField(db_column='address_Line_2', max_length=200, blank=True, null=True) # Field name made lowercase.
p_o_box = models.CharField(max_length=20, blank=True, null=True)
city = models.CharField(max_length=50)
country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='country_FK' , related_name='country_fk') # Field name made lowercase.
gender_fk = models.ForeignKey('Gender', models.DO_NOTHING, db_column='gender_FK') # Field name made lowercase.
bdate = models.DateField()
def __str__(self):
return 'User: ' + self.user_name
class Meta:
managed = False
db_table = 'buyer'
and after the registration User/Buyer can add more information such as first name , mobile phone etc.. in the profile page
As Willem van Onsem mentioned, use a ForeignKey in your Buyer model to reference to the user object:
class Buyer(models.Model):
#other stuff
user_fk = models.ForeignKey(User, on_delete=models.SET_NULL)
#other stuff
Or, if every Buyer is just one User and every User is just one Buyer, use a OneToOneField instead of a ForeignKey.
If you would then want to access the username/email/password you can use a query like this:
buyer = Buyer.objects.all().first()
buyer_email = buyer.user_fk.email

Django - having more than one foreignkey in the same model

models.py
class City(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=35)
countrycode = models.CharField(max_length=3)
district = models.CharField(max_length=200)
population = models.IntegerField(default='0')
class Country(models.Model):
code = models.CharField(primary_key=True, max_length=3)
name = models.CharField(max_length=52)
continent = models.CharField(max_length=50)
region = models.CharField(max_length=26)
surfacearea = models.FloatField()
indepyear = models.SmallIntegerField(blank=True, null=True)
population = models.IntegerField()
lifeexpectancy = models.FloatField(blank=True, null=True)
gnp = models.FloatField(blank=True, null=True)
gnpold = models.FloatField(blank=True, null=True)
localname = models.CharField(max_length=45)
governmentform = models.CharField(max_length=45)
headofstate = models.CharField(max_length=60, blank=True, null=True)
capital = models.IntegerField(blank=True, null=True)
code2 = models.CharField(max_length=2)
SQL For the models
for City
INSERT INTO city VALUES (3955,'Sunnyvale','USA','California',131760);
for Country
INSERT INTO country VALUES ('BHS','Bahamas','North America','Caribbean',13878.00,1973,307000,71.1,3527.00,3347.00,'The Bahamas','Constitutional Monarchy','Elisabeth II',148,'BS');
Question 1
In the above mentioned models how can i relate code in the Country.code to City.countrycode, i am not able to do so because Country model is declared after the City model.
Question 2
And how to link the Country.capital in the Country model which is a integer that relates to City.name.
Note
I am converting a .sql file with InnoDB Engine to Postgresql.
looks like you need declare foreign key related by string
class City(models.Model):
name = models.CharField(max_length=35)
countrycode = models.ForeignKey('Country', blank=True, null=True)
class Country(models.Model):
code = models.CharField(primary_key=True, max_length=3)
name = models.CharField(max_length=52)
capital = models.ForeignKey('Country', blank=True, null=True)

Django 1.11 not recognising Foreign Key model assignments

I am having an issue with 2 Foreign Key assignments in my django model. See models.py below:
from django.db import models
from django.contrib.auth.models import User
class userData(models.Model):
user = models.ForeignKey(User)
house = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=True, null=True)
street = models.CharField(max_length=150)
state = models.CharField(max_length=100)
postcode = models.CharField(max_length=20)
country = models.CharField(max_length=100)
telephone = models.CharField(max_length=20)
subscription = models.IntegerField(default=0)
active = models.IntegerField(default=0)
class area(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class country(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class city(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class foodType(models.Model):
food_type_name = models.CharField(max_length=100)
class restaurant(models.Model):
restaurant_name = models.CharField(max_length=100)
food_type = models.ForeignKey(foodType)
area = models.ForeignKey(area)
country = models.ForeignKey(country)
city = models.ForeignKey(city)
date_added = models.DateField()
main_image = models.ImageField(blank=True, null=True)
website = models.URLField(blank=True, null=True)
summary = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
featured = models.IntegerField(default=0)
class restaurantFeature(models.Model):
feature_name = models.CharField(max_length=100)
restaurant_id = models.ForeignKey(restaurant)
Django Foreign Key not working correctly
The image shows the Country and City, not showing correctly, like the FoodType and Area does. Theses show with the + buttons for adding, the mysql database is showing the key next to the fields. I have also tried renaming country and City adding Location after, thinking it could be something with these names.
Appreciate any help with this one.
You're having this issue because you need to reference ALL the models inside the admin.py. Django admin doesn't know what you're referencing.

Query using Joins in Django

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')

Django - Get objects which do NOT have any related objects

This may be a duplicate.
So I have:
class User(models.Model):
school = models.ForeignKey(School)
email = models.EmailField(max_length=254)
password = models.CharField(max_length=128)
firstname = models.CharField(max_length=50)
surname = models.CharField(max_length=50)
middlenames = models.CharField(max_length=100, blank=True)
utype = models.CharField(max_length=1, choices=(('a','Administrator'),('t','Staff'),('s','Student')))
lastlogin = models.DateTimeField(null=True)
active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
class Staff(User):
# Some methods
class Student(User):
form = models.CharField(max_length=20)
parentemail = models.EmailField(max_length=254)
parentphone = models.CharField(max_length=20)
class Placement(models.Model):
student = models.ForeignKey(Student)
email = models.EmailField(max_length=254)
name = models.CharField(max_length=100)
company = models.CharField(max_length=100)
position = models.CharField(max_length=50)
house = models.CharField(max_length=50)
street = models.CharField(max_length=50)
town = models.CharField(max_length=50)
county = models.CharField(max_length=50)
postcode = models.CharField(max_length=8)
phone = models.CharField(max_length=20)
length = models.IntegerField(null=True)
category = models.CharField(max_length=50)
date = models.DateField(null=True)
state = models.CharField(max_length=1, choices=(('A','In progress'),('B','Confirmed'),('C','Completed')))
created = models.DateTimeField(auto_now_add=True)
class Visit(models.Model):
placement = models.ForeignKey(Placement)
staff = models.ForeignKey(Staff)
date = models.DateField(null=True)
feedback = models.CharField(max_length=1000)
confirmed = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
And I want to retrieve all Placements which do not have any Visits (and the Student belongs to a particular School).
My views
def placements(request):
if request.session['utype'] == 't':
context['user'] = Staff.objects.get(pk=request.session['user'])
if request.method == 'POST':
placements = context['placements'] = Placement.objects.filter(student__school=school)
for choice in visits:
placement = Placement.objects.get(pk=choice)
visit = placement.NewVisit(user, placement.date, '', False)
visit.save()
return redirect('workxp:visits')
else:
context['placements'] = Placement.objects.filter(student__school=school, visit_set=None)
return render(request, 'workxp/staff/placements.html', context)
This is what I have so far from looking at other questions, but it doesn't seem to work...
no_visits = Placement.objects.filter(student__school=school_object, visit_set=None)
If I give a related name to the placement field in Visit, it works. Why not visit_set?
You need to use visit_set to reference the reverse relation since it's one to many
no_visits = Placement.objects.filter(student__school=school_object, visit_set=None)
or if you were to specify a nice related name...
class Visit(models.Model):
placement = models.ForeignKey(Placement, related_name='visits')
...
no_visits = Placement.objects.filter(student__school=school_object, visits=None)

Categories