Creating and fetching child records n Django
I have two models like:
class Manager(models.Model)
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=65535, null=False)
class Employee(models.Model)
id = models.AutoField(primary_key=True)
manager = models.ForeignKey(Manager)
name = models.CharField(max_length=65535, null=False)
When fetching all the employees for a manager, which would be the correct way to do it:
mgr = Manager.objects.get(id=1)
emps = Employees.objects.get(manager=mgr)
or
mgr = Manager.objects.get(id=1)
emps = Employees.objects.get(manager=mgr.id)
When creating both the parent and child objects, is it okay to do this:开发者_JAVA百科
emp = Manager.objects.create(name='John').employees.create(name='Johns Slave')
Neither =)
mgr = Manager.objects.get(id=1)
emps = mgr.employee_set.all()
And for your second one. No you'll need them seperately and like so:
mgr = Manager.objects.create(name='John')
emp = Employee.objects.create(name='Johns Slave', manager=mgr)
For the first one, you could just do
emps = Employees.objects.filter(manager=1)
assuming 1 is the manager id for which you need to retrieve employees.
精彩评论