我有2個車型,如這樣的:獲得來自ORM查詢所有外鍵在父表 - Django的
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的方式呢?
有道理。謝謝。我將如何反映一個OneToOneField?我會在'Assignment'中做'志願者=模型'一個一個場(志願者)'還是'志願者'中的相反?有什麼區別嗎? – hanleyhansen
不,沒有真正的區別 - 它只是取決於您想要存儲信息的位置。由於您的ForeignKey在分配上,所以您最好還是在那裏保留新的字段。 –