many to many in django
class Employee(Profile):
designation = models.ForeignKey(Designation)
keys = models.ManyToManyField(Key开发者_Python百科s)
parent = models.ManyToManyField(Parent, blank=True, null=True)
If i know some key id lets say key_id=12 how to query Employee for keys
(not sure if I understood your question, but) this will give you the key assigned to Employee object e
that has key_id=12
.
# assuming e is an Employee
key = e.keys.get(key_id=12)
Isc
answer is correct, but it can be broadened. Basically, in a model instance containing ManyToManyField
, that field becomes a Manager that can be used in a similar fashion to Model.objects
, i.e. most of QuerySet functions work as usual, as they have shortcuts inside the Manager.
There are also limitations specifing to such "related" Managers, as they are called in Django terminology, but it's outside the scope of this question I think,.
精彩评论