I have following models setup in my Django application
class School(models.Model):
name = models.TextField()
class Courses(models.Model):
name = models.TextField()
schools = ManyToManyField(School)
Now, I want to find out all schools which offer a particular course. For example, find all schools which offer biology and chemistry. What query can I use?
thanks
See lookup that span relationships in the manual:
class Courses(models.Model):
name = models.TextField()
schools = ManyToManyField(School, related_name='courses_set')
School.objects.filter(courses_set__name__in=('biology', 'chemistry'))
Related
class Author(models.Model):
name = models.CharField(max_length=50)
class Chapter(models.Model):
book = models.ForeignKey(Album, on_delete=models.CASCADE)
author = models.ManyToManyField("Author")
class Book(models.Model):
author = models.ManyToManyField("Author")
I am trying to show all related authors when I visit one author detail. To do that currently I do this to achieve this:
authors = []
for chapter in Author.objects.get(id=id).chapter_set.all():
authors.append(chapter.artists.all())
Is there any other way to do this by djangoORM
You can follow ManyToManyField relationships backwards in filters, in the case of the Author model you should be able to use chapter__ to access the Chapter.author relationship
authors = Author.objects.filter(chapter__author_id=id).distinct()
i'm a beginner in Django development (and MVC programming in general!)
considering the following example how could I translate these entities into models?
USER (id, name, surname)
ENGLISH_CERTIFICATION (id, code, name)
USER_CERTIFICATION (id, id_user, id_english_certification, date)
class User(models.Model):
name = models.CharField(max_length=64)
surname = models.CharField(max_length=64)
???
class EnglishCertification(models.Model):
code= models.CharField(max_length=2)
name = models.CharField(max_length=64)
???
Where i put the relationships and the field "date"?
Thank you!
If you want to create models that exactly represent the entities as you described, you could simply create an additional Model similar to:
class UserCertification(models.Model):
user = models.ForeignKey('User', on_delete=models.CASCADE)
english_certification = models.ForeignKey('EnglishCertification', on_delete=models.CASCADE)
date = models.DateField()
Of course you will need to adapt the code above depending on your needs. For more information you can have a look at:
https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_one/
Hope this helps
class Catalog(models.Model):
name = models.CharField(max_length=200)
no_of_pcs = models.IntegerField(null=True,blank=True)
per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2)
def __str__(self):
return self.name
class Company(models.Model):
name = models.CharField(max_length=200)
phone_number = models.IntegerField(null=True,blank=True)
user = models.ManyToManyField(User)
catalog = models.ManyToManyField(Catalog)
def __str__(self):
return self.name`***
The basic models documentation has a lot of info you'll need to know (including what you're asking for) and the official tutorial should put you through the fundamentals. Django's doc in general is pretty good, and the source is reasonably readable, so right there you have two great resources in addition to SO.
I'm starting my first Django web app [after completing the Django official tutorial and Django Girls tutorial].. I'm having some trouble wrapping my head around setting up models. I have something now that works, but I feel that it is quite inefficient and I rather learn the correct way before going forward..
Starting out - When learning a new programming language, a lot of people (on the internet) advise to pick a topic/hobby you enjoy and make a project out of it. I enjoy sports a lot and wanted to recreate a virtual scoreboard, similar to ESPN or any other sports web site.
My models.py currently looks like this -
class Game(models.Model):
# start_time = models.DateTimeField()
today = models.DateField(default=date.today)
game_id = models.AutoField(primary_key=True)
game_outcome = models.CharField(max_length=8)
game_quarter = models.CharField(max_length=1)
game_clock = models.PositiveSmallIntegerField()
away_team_id = models.CharField(max_length=3)
away_team_class = models.CharField(max_length=3)
away_team_city = models.CharField(max_length=13)
away_team_name = models.CharField(max_length=12)
away_team_score = models.PositiveSmallIntegerField()
home_team_id = models.CharField(max_length=3)
home_team_class = models.CharField(max_length=3)
home_team_city = models.CharField(max_length=13)
home_team_name = models.CharField(max_length=12)
home_team_score = models.PositiveSmallIntegerField()
but I feel like this is way too many variables and not the correct way to go about it. I have also tried something like this...
class Day(models.Model):
today = models.DateField(default=date.today)
class Game(models.Model):
game_id = models.AutoField(primary_key=True)
game_outcome = models.CharField(max_length=8)
game_quarter = models.CharField(max_length=1)
game_clock = models.PositiveSmallIntegerField()
away_team_id = models.CharField(max_length=3)
away_team_score = models.PositiveSmallIntegerField()
home_team_id = models.CharField(max_length=3)
home_team_score = models.PositiveSmallIntegerField()
class Team(models.Model):
team_id = models.ForeignKey('Team')
team_class = models.CharField(max_length=3)
team_city = models.CharField(max_length=13)
team_name = models.CharField(max_length=12)
Every Day has 0 to xx amount of games. Than every game has: outcome (null or 'FINAL'), current quarter ('1' or null), current clock ('00:00' or null), away team ('CHA'), away score ('99'), home team('TOR') and home score('102'). Then I would take the team id's and compare that to the class Team. Every Team has a class (for css: 'tor'), a city ('Toronto'), and full name ('Raptors').
Still it's not sticking in my head. I can get the all the information in a python shell and output to my html/css, but I feel it's inefficient. Also, every Day has it's own html page (similar to website.com/nba/scores/20150112/) and is filled with all the games from that day.
Sorry if this is too beginner to ask; I have spent a lot of time looking for answers and finally decided to post on stackoverlow (my first question ever).
Any information or advice would be greatly appreciated.
First of all you need to understand the more ForeignKeys you use the more load you put on the database. But it also depends a lot on the views.py code as well. Second of all you don't need to use team_id as a field name if you use a ForeignKey. Just mention the class name and it will automatically create an _id for the field.
Look at the following code:
class Game(models.Model):
start_time = models.DateTimeField()
today = models.DateField(default=date.today)
game_id = models.AutoField(primary_key=True) # You don't need this line, an id field is created for EVERY model class even if you don't specify it.
game_outcome = models.CharField(max_length=8)
game_quarter = models.CharField(max_length=1)
game_clock = models.PositiveSmallIntegerField()
away_team = models.ForeignKey('Team')
home_team = models.ForeignKey('Team')
class Team(models.Model):
team_class = models.CharField(max_length=3)
city = models.CharField(max_length=13)
name = models.CharField(max_length=12)
score = models.PositiveSmallIntegerField()
You can see that I have created another class by the name of Team and put four fields on that which was repeated in your original Game class. Then I have connected the Team class to the Game class with ForeignKey. If you install SQLiteBrowser and check out the database file then you will see that the away_team field is actually the away_team_id field in the database because Django takes care of that. You don't need to create id fields, just use relations like ForeignKey, ManyToManyField, etc. Off the top of my head this is the only thing that I can suggest.
Judging by the scope of this project you will not put too much pressure on the database with too many relations, so don't worry about that now. That' it. If you have any question more specific you can ask. Cheers! :)
P.S. I am not sure about your project details so use whichever relation you see fit, be it one-to-one, many-to-one or many-to-many, etc. Read the docs for more details. :)
I think the general idea of your model approach is good enough. Nevertheless, I'd encourage you to go through Django's ORM relationships documentation. It's ok if you want to use strings as your primary key, but let Django's ORM know that by using the proper model field. If you use primary and foreign keys (relationships), your dbms will create indexes over the necessary fields, resulting in more efficient queries. Let me know if this help! Good luck with your project!
UPDATE:
It would be something like this:
class Day(models.Model):
today = models.DateField(default=date.today)
class Game(models.Model):
game_outcome = models.CharField(max_length=8)
game_quarter = models.CharField(max_length=1)
game_clock = models.PositiveSmallIntegerField()
day = models.ForeignKey(Day, on_delete=models.CASCADE)
away_team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='away_team')
away_team_score = models.PositiveSmallIntegerField()
home_team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='home_team')
home_team_score = models.PositiveSmallIntegerField()
class Team(models.Model):
team_class = models.CharField(max_length=3)
team_city = models.CharField(max_length=13)
team_name = models.CharField(max_length=12)
Notice that I omitted all id fields, since django will use one automatically created, which behaves the same as AutoField. Also notice that since Game has two references to the same class (Team), it is necessary to provide the extra parameter related_name. Mor info about it in django docs about related_name.
This way, you can do things like
game = Game.objects.find(1)
away_team_name = game.away_team.team_name
You can access the associated Team class in the away_team variable. No need to call away_team_id at all.
The following models describe a vulnerability and the URLs out on the internet that reference that vulnerability. Assume that each URL only ever talks about 1 vulnerability, and that many URLs will discuss that vulnerability. Is this the correct way to lay out the model?
class Vuln(models.Model):
pub_date = models.DateTimeField("Publication Date")
short_description = models.CharField("Description", max_length=70)
reference_urls = models.ForeignKey(Url, unique=True, blank=True, verbose_name="Reference URLs")
vendor = models.ForeignKey(Vendor, verbose_name="Vendor")
class Url(models.Model):
url = models.URLField("URL", max_length=200)
The Admin application gives a 'select' box for the reference URLs, which isn't what I want. When I add a new vulnerability object, all of the existing URLs that have been entered show up in that dropdown, which is again unnatural. I feel like this should behave very similar to how a blog comment would, ie. the comment applies to a single blog entry and none other and that one blog entry may have many comments. How do I express this in a Django model?
It should be more like this:
class Vuln(models.Model):
pub_date = models.DateTimeField("Publication Date")
short_description = models.CharField("Description", max_length=70)
vendor = models.ForeignKey(Vendor, verbose_name="Vendor")
class Url(models.Model):
url = models.URLField("URL", max_length=200)
vulnerability = models.ForeignKey(Vuln)
If you're saying each Url talks about a specific vulnerability, then there is your relation in the Django DBM :)
As for the vendor field, you simply add another class, much like Class Vuln. For example:
class Vendor(models.Model):
field_names_go_here = models.TextField(max_length=70)
short_description = models.CharField("Description", max_length=70)
Hope this helps!
Regards, Alex