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?
Related
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).
Here My Branch table and Store Table
How many branch record available in store table and count. I'm try it but can't get it.
class Branch(models.Model): # Branch Master
status_type = (
("a",'Active'),
("d",'Deactive'),
)
name = models.CharField(max_length=100, unique=True)
suffix = models.CharField(max_length=8, unique=True)
Remark = models.CharField(max_length=200, null=True, blank=True)
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=1, choices = status_type, default = 'a')
def __str__(self):
return self.name
class Store(models.Model):
status_type = (
("y",'Yes'),
("n","No")
)
branch = models.ManyToManyField(Branch)
asset = models.ForeignKey(Asset,on_delete=models.CASCADE)
asset_code = models.CharField(max_length=100, null=True, blank=True, unique = True)
model = models.CharField(max_length=250)
serial_no = models.CharField(max_length=200)
vendor = models.ForeignKey(Vendor,on_delete=models.CASCADE)
invoice_no = models.CharField(max_length=50)
purchase_date = models.DateField()
store_status = models.CharField(max_length=1, choices = status_type, default = "y", blank = True)
store_date = models.DateTimeField(null = True, blank = True)
assige = models.CharField(max_length=1, choices = status_type, default = "n", blank = True)
assige_date = models.DateTimeField(null = True, blank = True)
scrap = models.CharField(max_length=1, choices = status_type, default = "n", blank = True)
scrap_date = models.DateTimeField(null = True, blank = True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
create_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
Query
get store object
store_obj = Store.objects.get( id= 5)
try to get count of branch record
tempcount = Store.objects.filter( branch = store_obj ).count()
I'm tired to get branch count.
To get the count of branch records associated with a store, you should query the Branch model instead. Since reverse m2m queries are supported, you can simply do:
branch_count = Branch.objects.filter(store=store_obj).count()
There are three tables which are:
models.py
class Student(models.Model):
gen_choices = (
("Male", "Male"),
("Female", "Female"),
("Third", "Third"),
)
enrollNo = models.IntegerField(default=add_one)
fname = models.CharField(validators=[max_len_check], max_length=26)
lname = models.CharField(validators=[max_len_check], max_length=26)
gender = models.CharField(max_length=6, choices=gen_choices)
dob= models.DateField()
address = models.CharField(max_length=256)
email = models.EmailField()
mobile = models.BigIntegerField()
status = models.BooleanField(null=True)
userID = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.FileField(upload_to="stdimages/", null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Entexaminfo(models.Model):
entexamses = (
("June Session", "June Session"),
("December Session", "December Session"),
)
approve_choice = (
("Pending", "Pending"),
("Accepted", "Accepted"),
("Rejected", "Rejected"),
)
ename = models.CharField(max_length=16, choices=entexamses)
enrollno = models.OneToOneField(Student, on_delete=models.CASCADE)
#programs = models.ManyToManyField(Programs, related_name='proNames', default=0)
program = models.ManyToManyField(Programs, default=0)
center = models.ForeignKey(Excenter, on_delete=models.CASCADE)
remarks = models.CharField(validators=[max_len_check], max_length=256, default="-")
#status = models.BooleanField()
status = models.CharField(max_length=8, choices=approve_choice, default="Pending")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
# for admin pannel to display for correction
def __str__(self):
return self.ename
class Ex_schedule(models.Model):
exDate = models.DateField()
exTime = models.TimeField()
exDuration = models.CharField(validators=[max_len_check], max_length=26)
programs = models.OneToOneField(Programs, on_delete=models.CASCADE)
exRemarks = models.CharField(max_length=256, null=True)
exStatus = models.BooleanField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
# for admin pannel to display for correction
def __str__(self):
return self.exDate
class Programs(models.Model):
proName = models.CharField(validators=[max_len_check], max_length=26)
proDuration =models.CharField(validators=[max_len_check], max_length=26)
proFees = models.IntegerField(null=True)
proDetails = models.CharField(validators=[max_len_check], max_length=26, null=True)
proStatus = models.BooleanField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = models.Manager
# for admin pannel to display for correction
def __str__(self):
return self.proName
I want to filter data from three tables (i.e. Student, Entexaminfo & Ex_schedule) giving a enrollno of student table, But I am not being able to filter data from Ex_schedule table because a student can choose more than one subject, according to chosen subjects data should be filter from Ex_schedule table. For this I have tried following codes but program id i have given manually, I want to replace it.
views.py
#login_required(login_url='/user/login')
def hall_ticket(request):
query = request.GET['enrollno']
if query:
entedetail = Student.objects.filter(enrollNo=query)
for obj in entedetail:
global id #To avoid 'local variable 'id' referenced before assignment' error message
id = obj.id
ent1 = Entexaminfo.objects.filter(enrollno=id)
esch = Ex_schedule.objects.filter(programs=1)
params = {'entedetails': entedetail, 'ent1': ent1, 'query': query, 'esch': esch, 'title': 'Entrance Exam Hall Ticket'}
else:
params = {'error': 'Please Enter Your Enrollment No.', 'title': 'Entrance Exam Hall Ticket'}
return render(request, 'hall_ticket.html', params)
Please guide me for it.
Good day.
Am having a model called AddInv
AddInv(models.Model):
client = models.ForeignKey(User, null=True)
description = models.CharField(max_length = 100)
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField()
sold = models.PositiveIntegerField(default=0)
details = models.CharField(max_length = 100)
country = models.ForeignKey(Signup, null = True)
def __str__(self):
return self.country
Model for Signup is
class Signup(models.Model):
user = models.OneToOneField(User)
phone_number = models.PositiveIntegerField( null=True)
zipcode = models.PositiveIntegerField(null=True)
street = models.CharField(max_length = 75, null=True)
city = models.CharField(max_length = 75, null=True)
state = models.CharField(max_length = 75, null= True)
country = models.CharField(max_length = 32, null=True, choices = CATEGORIES)
def __str__(self):
return self.country
and a views to filter by country
def homepage(request): # Client View
context = {}
items = get_object_or_404(AddInv, country="USA")
print "Items", items
return render(request, "selly/homepage.html", {'items': items})
Am having error pointing to
items = get_object_or_404(AddInv, country="USA")
What could be wrong with the code
Try this. Just an assume
items = get_object_or_404(AddInv, country__country="USA")
I used
items = AddInv.objects.filter(country__country="USA")
which worked
How can I get the foreign key values? I have a common vehicle model that links to the year, series, engine type, body style, transmission and drive train...all as foreign keys. I'd like to get the values of these fields for my app, but I'm stuck as to how I'd go about them. Any ideas will be highly appreciated.
class Model(models.Model):
model = models.CharField(max_length=15, blank=False)
manufacturer = models.ForeignKey(Manufacturer)
date_added = models.DateField()
def __unicode__(self):
name = ''+str(self.manufacturer)+" "+str(self.model)
return name
class Year(models.Model):
ALPHA_NUMERIC_CHOICES = (
('1', 'Numeric'),
('A', 'Alphabetic'),
)
year = models.PositiveSmallIntegerField()
position_7_char = models.CharField(max_length=1, choices=ALPHA_NUMERIC_CHOICES)
position_10 = models.CharField(max_length=1, blank=False)
def __unicode__(self):
return unicode(self.year)
class Series(models.Model):
series = models.CharField(max_length=20, blank=True)
model = models.ForeignKey(Model)
date_added = models.DateField()
def __unicode__(self):
name = str(self.model)+" "+str(self.series)
return name
class CommonVehicle(models.Model):
year = models.ForeignKey(Year)
series = models.ForeignKey(Series)
engine = models.ForeignKey(Engine)
body_style = models.ForeignKey(BodyStyle)
transmission = models.ForeignKey(Transmission)
drive_train = models.ForeignKey(DriveTrain)
def __unicode__(self):
name = ''+str(self.year)+" "+str(self.series)
return name
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6, blank=False)
vin = models.CharField(max_length=17, blank=False)
common_vehicle = models.ForeignKey(CommonVehicle)
exterior_colour = models.ForeignKey(ExteriorColour)
interior_colour = models.ForeignKey(InteriorColour)
interior_type = models.ForeignKey(InteriorType)
odometer_unit = models.ForeignKey(OdometerUnit)
status = models.ForeignKey(Status)
odometer_reading = models.PositiveIntegerField()
selling_price = models.PositiveIntegerField()
purchase_date = models.DateField()
sales_description = models.CharField(max_length=60, blank=False)
def __unicode__(self):
return self.stock_numberodels.ForeignKey(CommonVehicle)
You need the actual IDs? Try something like my_vehicle_ref.series.id.
Also, I hope you know that the series attribute right there is really an instance of Series, so you could access any of it's properties, e.g., my_vehicle_ref.series.model.model.