I have 3 tables:
Employee
Survey
Manager
Employee tbl has direct relationship with both tables, however there is no direct relationship between survey and manager.
I am trying to create a chart/scorecard which does the average score on a question in surgery tbl. This works fine, however I would like to filter this by managers name from manager tbl, and this does not work.
Any help please?
If you configure a 1-many relationship from Manager to Employee, and a 1-many relationship from Employee to Survey then filters will flow from Manager to Employee to Survey.
Related
I have two models Students, University. By using this, student can apply for a course in university and the requirements is when a student apply for a course in university, i need to create a application ( planning to create separate model for application )
And this application can been accessed by both student & university. The purpose of making both access the application is because there are many post apply data's to be manipulated later !
So how to create a common application table - so both can access or its not effecient to create a seprate table ?
Please guide on how to tackle this !
Option1: Can a many to many be combined with Student and University to create a application model
Option2: Add manytomany field to students model itself with University as foreign key ?
I have records about more than 1 million so am bit concerned about efficiency ! Which is better option to handle two way communication
The best way to handle this would be to have the intermediate model Application to contain foreign keys to both Student and University.
Having both foreign keys in the Application model would guarantee a many-to-many relationship between the Student and University.
The solution would be like so:
class Student(models.Model):
email = models.EmailField(max_length=255)
class University(models.Model):
name = models.TextField()
class Application(models.Model):
applicant = models.ForeignKey(
"Student",
on_delete=models.CASCADE
)
university = models.ForeignKey(
"University",
on_delete=models.CASCADE
)
Option1: Can a many to many be combined with Student and University to create an application model
Option1 is answered by Ren.
For explanation, you may check Django Features and Libraries
University of Michigan Video
Option2: This won't fulfill your requirements. Indeed Django will automatically generate a table to manage many-to-many relationships. You need to manually specify the intermediary table, you can use the through option to specify the Django model that represents the intermediate table that you want to use. i.e. Option 1
See ManyToManyField official doc.
I'm using python and psycopg2 to scrape some data and insert them into my database.
I've already created the movies and actors tables inside my Django models.py and inside my movies table, there is a many to many relationship between movies and actors table.
below is my models.py:
class Movie(models.Model):
name = models.CharField(max_length=55)
summary = models.TextField(max_length=1024)
actor = models.ManyToManyField(Actor, blank=True)
when I create a movie from Django-admin I select which actors are included in the movie and everything works fine and all the related actors for that movie will show up on my website.
But the problem is that when I try to insert scraped data into my database outside of my Django project folder, the related actors won't be shown on my website because obviously, I have not set the many to many relationship between them.
I have tried creating a junction table using SQL commands which gets the movie id and the actor's id and links them together but I don't know how I should tell Django to use that table and show the related actors for each movie.
This is the SQL code I use to insert into my db:
INSERT INTO movies(name, summary)
VALUES ('movie name', 'sth')
and the code to insert to actors table:
INSERT INTO actors(name, bio)
VALUES ('actorname', 'sth')
Both actors and movies table have auto generated id and I insert them insto the junction table using the code below:
INSERT INTO movie_actors (actor_id, movie_id)
VALUES (
(SELECT actor_id from actors where name='actor name'),
(SELECT movie_id from movie where name='movie name')
)
Am I doing it right?
I would really appreciate it if someone could help me with this.
Django automatically creates a table for many2many relationships. From docs:
ManyToManyField.through
Django will automatically generate a table to manage many-to-many relationships. However, if you want to manually specify the intermediary table, you can use the through option to specify the Django model that represents the intermediate table that you want to use.
The most common use for this option is when you want to associate extra data with a many-to-many relationship.
So you must find the name of the table that django had already created.
Secondly, I suggest that you use django's ORM instead of raw queries so you don't have these kind of problems anymore.
Django automatically creates a through table for M2M relations, if you need you can specify custom through table. In your case I think there is no need of custom through table.
I using Django ORM instead of writing raw query.
INSERT INTO movies(name, summary) VALUES ('movie name', 'sth')
instead of tis raw query you can use the following ORM query:
movie = Movie.objects.create(name="movie name", summary="movie sammuary")
This will create a movie entry in the Movie table.
Next to create user entry you can use the following query:
actor = Actor.objects.create(name="actor name", bio="actor bio")
Now you created the entries in both the table, next you can establish the realtion, for that you have to use the following query:
movie.actor.add(actor)
Incase if you want to add multiple actors at the same time, you create multiple actors object and use following query:
movie.actor.add(actor1, actor2, actor2)
For more details you can check django's offical documentation
I have a table employees with employee_id as a primary key, some of the employees are managers and managers can also have managers.
So I wanted to add a manager_id field to the table employees which is the employee_id of the manager of the employee. I tried to create a one to many relationship between the table and itself but without success.
In the employees class I have added the following:
id_manager = models.ForeignKey(employees, on_delete=models.PROTECT)
NameError: name 'employees' is not defined
I am pretty new to django, any idea how to code this?
Thanks.
The documentation for ForeignKey covers this case explicitly:
To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self', on_delete=models.CASCADE).
I've read of folks talking about using ForeignKey for a One-To-Many relationship in Django, but that's not what I'm looking for. Suppose I have a model called Club defined simply as:
class Club(models.Model):
name = models.CharField(max_length = 64)
What I want is to add a field called owners that is a one-to-many relationship to users (the User model). I don't want to add a ForeignKey to User that references Club because that will clutter User. I really want a field in the Club model that maintains the relationship to 0, 1, or more Users that are considered owners of the Club. Anyone have any ideas?
What you are looking for is a Many-To-Many relationship.
In a many-to-many relationship, each row in table A can have many (zero or more) matching rows in table B, and each row in table B can have many matching rows in table A. Each club can have many owners, and each owner can have many clubs, for example.
Adapted from: http://my.safaribooksonline.com/book/databases/sql/9780321584069
I'm building an ecommerce website.
I have a Product model that holds info common to all product types:
class Product(models.Model):
name=models.CharField()
description=models.CharField()
categories = models.ManyToManyField(Category)
Then I have SimpleProduct and BundleProduct that have FK to Product and hold info specific to the product type. BundleProduct has a m2m field to other Products.
class SimpleProduct(Product):
some_field=models.CharField()
class BundleProduct(Product):
products = models.ManyToManyField(Product)
When displaying the catalog I'm making one query against the Product model
and then another query per product to get the additional info.
This involve a large number of queries.
I can improve it by using select_related on the simpleproduct and bundleproduct fields.
I can further improve it by using the select_reverse app for m2m fields like categories.
This is a big improvement but there are more required queries because a BundleProduct have several products which can also have relations to other products (configurable product).
Is there a way to have a single query against Product that will retrieve the m2m categories, one2one SimpleProduct and BundleProduct and the BundleProduct's products?
Will this custom query look like a django queryset with all the managers and properties?
Thanks
You can possibly take a look at the extra method of querysets. May give you the opportunity to add some additional fields. But if you want raw queries, you can use the raw method of managers, these will return a type of queryset, that will not however harness the full power of normal querysets but should be enough for your concerns. On that same page the execute method is also shown, this is for truly custom sql that can't even translate into raw querysets.