我有2个这样的模型:
class Volunteer(models.Model):
first_name = models.CharField(max_length=50L)
last_name = models.CharField(max_length=50L)
address = models.CharField(max_length=100L)
city = models.CharField(max_length=100L)
state = models.CharField(max_length=2L)
zip = models.CharField(max_length=5L)
skype = models.CharField(max_length=50L)
email = models.CharField(max_length=50L)
age = models.IntegerField(max_length=2L)
phone_mobile = models.CharField(max_length=50L)
phone_home = models.CharField(max_length=50L)
gender = models.CharField(max_length=1)
class Assignment(models.Model):
volunteer = models.ForeignKey(Volunteer)
department = models.ForeignKey(Department)
role = models.ForeignKey(Role)
location = models.CharField(max_length=100L, blank=True, null=True)
我正在努力争取所有志愿者以及他们的任务。以下作品:
volunteers = Volunteer.objects.all().order_by('last_name')
for volunteer in volunteers:
assignment = Assignment.objects.get(volunteer=volunteer)
volunteer.assignment = assignment
但是有更多的Django方式吗?
答案 0 :(得分:1)
在您当前的模型结构中,每位志愿者都可以进行多项任务。因此,没有志愿者的“任务”这样的事情。也许你打算使用OneToOneField而不是ForeignKey,在这种情况下你会自动从Volunteer获得一个“赋值”访问器,使你的循环变得冗余。
答案 1 :(得分:1)
您可以使用FOO_set获取志愿者的所有作业,更多here in docs:
volunteer.assignement_set.all()