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)
Related
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 have a table in models.py with class name registration and another table profileimage with foreignkey relation with registration model now i want to
get verify the email address by using profileimage table
models.py
class Registration(models.Model):
YourName = models.CharField(max_length=30)
Email = models.EmailField(max_length=254,verbose_name='email')
password = models.CharField(max_length=254,verbose_name='password',null=True)
PhoneNumber = models.IntegerField(null=True,verbose_name='email')
CompanyName = models.CharField(max_length=30)
WebSiteName = models.CharField(max_length=30)
NumberOfEmplyes = models.IntegerField(null=True)
YourRoleInCompany = models.CharField(max_length=100)
SoftwareUsedBefore = models.CharField(max_length=30)
Turnout2017 = models.IntegerField(null=True)
Turnover2016 = models.IntegerField(null=True)
Description = models.CharField(max_length=30)
ClientArgument = models.CharField(max_length=2000,null=True)
PaymentsPlan = models.CharField(max_length=100,null=True)
class ProfileImages(models.Model):
MemeberName = models.OneToOneField('Registration',on_delete=models.CASCADE,blank=True)
profile_image = models.ImageField(upload_to='media/profile_image',default=True,null=True)
def __str__(self):
return "user profile image"
now for example i have email adress which i get from sessions now e.g example#stack.com now i want to use this email to fillter record in this way.
profile_image=
ProfileImages.objects.filter(Registration__Email=email).select_related()
let me know what is the exact way to perform this query
ProfileImages.objects.get(MemeberName__email=email)
I think I would do it as follows
class ProfileImages(models.Model):
profile_image = models.ImageField(upload_to='profile_image',blank=True,null=True)
...
And in the Registration
class Registration(models.Model):
YourName = models.CharField(max_length=30)
Email = models.EmailField(max_length=254,verbose_name='email')
....
image_profile = models.ForeignKey(
ProfileImages, verbose_name='Profile Image', on_delete=models.CASCADE, blank=True, null=True)
Notice, that 'media' word in upload_to it is better to define it in settings.py
I have multiple models and i want to display them all on one page in django admin.
Some of these have no relationship(fk,onetoone,mm).
how i can achieve that?
class Category(models.Model):
name = models.CharField(max_length=100)
class Industry(models.Model):
name = models.CharField(max_length=100)
class SampleImages(models.Model):
image = models.ImageField(upload_to='images/tile_images')
category = models.ManyToManyField(Category)
industry = models.ManyToManyField(Industry)
class SampleColor(models.Model):
image = models.ImageField(upload_to='images/tile_color')
name = models.CharField(max_length=25)
class OrderDetail(models.Model):
name_in_logo = models.CharField( max_length=150)
slogan = models.CharField(max_length=20)
describe_website_and_audience = models.TextField()
How to join 3 or more tables in django (ORM ) and fetch the results?
Have created 3 models:
1.student
2.marks
3.details
class Student:
s_id = models.IntegerField(primary_key=True)
s_name = models.CharField(max_length=100)
class Marks:
school_id = models.IntegerField(primary_key=True)
s_id = models.ForeignKey(Student, on_delete=models.CASCADE)
score = models.IntegerField()
status = models.CharField(max_length=30)
class Details:
address_city = models.CharField(max_length=30)
emailid = models.EmailField()
school_id = models.ForeignKey(Marks,on_delete=models.CASCADE)
accomplishments = models.TextField()
I need to join these 3 tables and fetch student name,score,status,address_city,email_id,accomplishments.
In SQL we can write like this:
select s_name, score, status, address_city, email_id,
accomplishments from student s inner join marks m on
s.s_id = m.s_id inner join details d on
d.school_id = m.school_id;
Please let me know how to achieve same thing using DJANGO codes.
Some Suggestions for given models:
models.py:
class Student:
name = models.CharField(max_length=100)
class Marks:
student = models.ForeignKey(Student, on_delete=models.CASCADE)
score = models.IntegerField()
status = models.CharField(max_length=30)
class Details:
address_city = models.CharField(max_length=30)
emailid = models.EmailField()
school = models.ForeignKey(Marks,on_delete=models.CASCADE)
accomplishments = models.TextField()
Now, Create your mapping model as we create mapping table in sql:
class StundetMarksDetailsMap:
student = models.ForeignKey(Student, on_delete=models.CASCADE)
marks = models.ForeignKey(Marks, on_delete=models.CASCADE)
details = models.ForeignKey(Details, on_delete=models.CASCADE)
Now you can create your own queryset as you want in views.py or where you want:
class StudentView(generic.DetailsView):
model = Student
template = student_details.html
//this will return all values related student
def get_queryset(self):
return StundetMarksDetailsMap.objects.filter(student=Student)
Basically this get_queryset returns objects of models which are related to stundet which was picked, use returned objects of Details and Marks to call their corresponding fields in your template. Also use only those fields which you want to display.
Hope this works for you too. All the best :)
I think you should keep it simple rather than complicating models which won't be great when you have a lot of data. Keep the student model as the main Class. And store all other info in other tables.
class Student:
name = models.CharField(max_length=100)
marks = models.ForeignKey(Marks,on_delete=models.CASCADE)
school = models.ForeignKey(School,on_delete=models.CASCADE)
class Marks:
score = models.IntegerField()
status = models.CharField(max_length=30)
class Details:
address_city = models.CharField(max_length=30)
emailid = models.EmailField()
accomplishments = models.TextField()
class School:
name = models.CharField(max_length=30)
details = models.ForeignKey(Details)
Now do the below query
student = Student.objects.filter(pk=student_id).filter(school_pk=school_id)
print student.name
print student.marks.score
print student.marks.status
print student.details.address_city
For your current models, it's difficult to query. But you can try writing SQL queries itself. Something like this
Blog.objects.extra(
select={
'entry_count': 'SELECT COUNT(*) FROM blog_entry WHERE blog_entry.blog_id = blog_blog.id'
},
)
Follow this
https://docs.djangoproject.com/en/2.1/ref/models/querysets/#extra
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.