python - Use multiple foreign keys -
i'm beginner on django , bit more advanced on python. i'm amazed django , i've been playing week now. looked lot of tutorials , stackoverflow questions/answers , discovered lot.
however, i'm still little bit lost when comes onetomany / foreign key relationships , way access it. had @ "library/book" example of official documentation still trying figure out how solve below problem.
[explanations]
- i have users (already created)
- to django-built users, added profile (onetoonefield)
- the profile contains 1 item each user: title (foreign key)
- the title in turn comes existing list of available titles
- finally, have opportunities (a class) has 1 user linked (foreign key)
in models.py
class profilestatus(models.model): """ table of available titles users """ status = models.charfield(max_length=100) def __str__(self): return self.status class profile(models.model): """ add title existing user """ user = models.onetoonefield(user, on_delete=models.cascade) title = models.foreignkey(profilestatus, on_delete=models.cascade) class opportunitystatus(models.model): """ status opportunity """ status = models.charfield(max_length=100) def __str__(self): return self.status class opportunity(models.model): """ opportunity """ name = models.charfield(max_length=100, default='') director = models.foreignkey(user, on_delete=models.cascade) status = models.foreignkey(opportunitystatus, on_delete=models.cascade) def __str__(self): return self.name
[what i'm looking for]
i know how would:
- for users having 'director' title
- get list of opportunities linked director
- then filter list down opportunities have status 'alive' passed view (that can manage)
generally use double underscore syntax follow relations. so, example, users have title of director, do:
user.objects.filter(profile__title__status='director')
however, if want opportunities rather users, need start opportunity model. so:
opportunity.objects.filter(status__status='alive', director__profile__title__status='director')
this query might less horrible if made opportunity point profile, rather user.
Comments
Post a Comment