how to add new foreign key in my old django models? - django

I have a model name Employee now i want to add a new fields in this model which will be a foreign key of Department model.I try to solve it the following way but i get error like
django.db.utils.IntegrityError: The row in table 'employee_verification_employee' with primary key 'UP-0319001' has an invalid foreign key: employee_verification_employee.department_id contains a value '03' that does not have a corresponding value in employee_verification_department.id.
class Department(models.Model):
name = models.CharField(max_length=100)
id = models.CharField(primary_key=True,max_length=10)
class Employee(models.Model):
name = models.CharField(max_length=100)
department = models.CharField(max_length=100,choices = Departments)
date_of_joining = models.DateField()
employeed = models.BooleanField(default = True)
email = models.EmailField(max_length = 254)
blood_group = models.CharField(max_length=50)
designation = models.CharField(max_length=100)
image = models.ImageField(upload_to='employee_images',default = "")
number = PhoneField(blank=True, help_text='Enter Contact Number')
emergency_number = PhoneField(blank=True, help_text='Enter Contact Number')
id = models.CharField(primary_key=True, max_length=200)
department_new = models.ForeignKey(Department,on_delete=models.CASCADE,blank=True)
def save(self, *args, **kwargs):
if not self.id:
nth_member = Employee.objects.filter(department = self.department).count()+1
self.id = "UP-" + self.department + self.date_of_joining.strftime("%y")+"{:03d}".format(nth_member)
print(self.id)
super(Employee, self).save(*args, **kwargs)
def __str__(self):
return self.name + "--"+ self.designation``
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/xdRMd.png

As #trigo said, all you need is:
class Department(models.Model):
name = models.CharField(max_length=100)
class Employee(models.Model):
name = models.CharField(max_length=100)
department = models.CharField(max_length=100,choices = Departments)
date_of_joining = models.DateField()
employeed = models.BooleanField(default = True)
email = models.EmailField(max_length = 254)
blood_group = models.CharField(max_length=50)
designation = models.CharField(max_length=100)
image = models.ImageField(upload_to='employee_images',default = "")
number = PhoneField(blank=True, help_text='Enter Contact Number')
emergency_number = PhoneField(blank=True, help_text='Enter Contact Number')
department_new = models.ForeignKey(Department,on_delete=models.CASCADE,blank=True)
And Django will take care of the rest (ids).

Related

Django models - how to assign as ForeignKey

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

How to link two databases together?

I have 2 databases that are supposed to be linked by a foreign key: DealershipListing and Dealers.
Here are their models:
class Dealer(models.Model):
dealersName = models.TextField(('DealersName'))
zipcode = models.CharField(("zipcodex"), max_length = 15)
zipcode_2 = models.CharField(("zipCode"), max_length = 15)
state = models.CharField(("state"), max_length=5)
address = models.TextField(("Address"))
ids = models.BigIntegerField(("ids"), primary_key=True)
def __str__(self):
return self.dealersName
class DealershipListing(models.Model):
uniqueID = models.IntegerField(("CarID"), primary_key=True)
vincode = models.CharField(('vinCode'), max_length=255)
price = models.CharField(('price'), max_length=30)
msrp = models.CharField(('msrp'), max_length=30)
mileage = models.CharField(('mileage'), max_length=9)
is_new = models.BooleanField(('isNew'))
first_seen = models.CharField(("first_seen"), max_length=15)
last_seen = models.CharField(("last_seen"), max_length=15)
model = models.CharField(("Models"), max_length= 255)
make = models.CharField(("Make"), max_length=255)
year = models.CharField(("Year"), max_length= 4)
ids = models.ForeignKey(Dealer, on_delete=CASCADE)
color = models.CharField(("ExtColor"), max_length=255, null=True, blank = True)
intcolor = models.CharField(("IntColor"), max_length=255, null=True, blank=True)
def __str__(self):
return self.year + " " + self.make + " " + self.model
But when I go check the admin database, the DealershipListing is a dropdown of the names of every dealership in the Dealer model, but the ids on the DealershipListing model is placed in the place of color. What am I doing wrong? How do I connect each car in the DealershipListing to their Dealership by the ids?

generate random value form other field value in Django

I have a booking system for bank line :
this is my model for the customer:
class Customer(models.Model):
customer_bank = models.ForeignKey('Bank', on_delete=models.SET_NULL,related_name='coustmer_bank' ,null=True)
customer_branch = models.ForeignKey('Branch', on_delete=models.SET_NULL,related_name='coustmer_branch',null=True)
booking_id = models.CharField(max_length=120, blank= True,default=increment_booking_number)
identity_type = models.ForeignKey('IdentityType',on_delete=models.SET_NULL,related_name='identity_type',null=True)
identity_or_passport_number = models.CharField(max_length=20)
bank_account_no = models.CharField(max_length=15)
Done = models.BooleanField(default=False)
booking_date_time = models.DateTimeField(auto_now_add=True, auto_now=False)
Entrance_date_time = models.DateTimeField(auto_now_add=False, auto_now=True)# Must be modified to work with Entrance Date and Time
def __str__(self):
return self.booking_id
I need to generate a random value for booking_id field depends on bank_number and the branch_number and the Customer id so how can I do that? help please
You can overide the save method of the model
class Customer(models.Model):
customer_bank = models.ForeignKey('Bank', on_delete=models.SET_NULL,related_name='coustmer_bank' ,null=True)
customer_branch = models.ForeignKey('Branch', on_delete=models.SET_NULL,related_name='coustmer_branch',null=True)
booking_id = models.CharField(max_length=120, blank= True,default=increment_booking_number)
identity_type = models.ForeignKey('IdentityType',on_delete=models.SET_NULL,related_name='identity_type',null=True)
identity_or_passport_number = models.CharField(max_length=20)
bank_account_no = models.CharField(max_length=15)
Done = models.BooleanField(default=False)
booking_date_time = models.DateTimeField(auto_now_add=True, auto_now=False)
Entrance_date_time = models.DateTimeField(auto_now_add=False, auto_now=True)# Must be modified to work with Entrance Date and Time
def __str__(self):
return self.booking_id
def get_booking_id(self):
bank_number = self.bank_number
branch_number = self.branch_number
id = # logic for calculating boking ID from bank_number, branch_number and other fields accessible from self.<field_name>
return id
def save(self, *args, **kwargs):
self.booking_id = self.get_booking_id()
super(Customer, self).save(*args, **kwargs)

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.

using "primary" field in django model

i have two models: Address and Phone. Inside each model, rests a "Default" boolean field. What I need it to do, is if I submit a True answer in a form, then all other records must be set to False for that user.
How do I accomplish this?
class Address (models.Model):
User = models.ForeignKey(User)
Primary = models.BooleanField(default=True)
Street = models.CharField(max_length=500)
City = models.CharField(max_length=50)
State = models.CharField(max_length=40)
Zip = models.CharField(max_length=20)
County = models.CharField(max_length=20)
Country = models.CharField(max_length=50, default="United States")
Latitude = models.FloatField(null=True, blank=True)
Longitude = models.FloatField(null=True, blank=True)
class Meta:
verbose_name_plural = "Addresses"
def __str__(self):
primary = 'PRIMARY Address for ' if self.Primary else 'Address for '
return primary + self.User.first_name + ' ' + self.User.last_name
def save(self, *args, **kwargs):
geolocator = Nominatim()
location = geolocator.geocode("{} {}, {}, {}".format(self.Street, self.State, self.Zip, self.Country))
self.Latitude = location.latitude
self.Longitude = location.longitude
super(Address, self).save(args, *kwargs)
class Phone (models.Model):
User = models.ForeignKey(User)
Primary = models.BooleanField(default=True)
Country_Code = models.CharField(max_length=5, default="001")
Area_Code = models.CharField(max_length=5, blank=True, null=True)
Number = models.CharField(max_length=20, blank=True, null=True)
def __str__(self):
return self.Country_Code + "-" + self.Area_Code + "-" + self.Number
You can use post_save signal or override save method. Following is a simple snippet. If you want to keep consistent, put the these queries in a transaction.
def save(self, *args, **kwargs):
geolocator = Nominatim()
location = geolocator.geocode("{} {}, {}, {}".format(self.Street, self.State, self.Zip, self.Country))
self.Latitude = location.latitude
self.Longitude = location.longitude
super(Address, self).save(args, *kwargs)
Address.objects.exclude(id=self.id).update(Primary=False)