2013-07-26 48 views
-1

我是新編寫Django模型。我想要一個Person模型,每個人都有不同數量的職位。在Django中,如何設置具有包含多個其他模型實例的字段的模型?

from django.db import models 

class Person(models.Model): 
    first_name = models.CharField(max_length=30) 
    last_name = models.CharField(max_length=30) 
    positions = models.ForeignKey('Position') 

class Position(models.Model): 
    person = models.ForeignKey(Person) 
    company = models.CharField(max_length=200) 
    summary = models.TextField() 
    start_date = models.DateField() 
    end_date = models.DateField() 
    currently_there = models.BooleanField() 

我該如何設置它,讓一個人可以有多個職位?

回答

1

你有什麼是正確的(你有一個人有很多職位)。

我最初認爲ManyToManyField但我看到這確實是一個one to many關係,如果位置是一個人的唯一。

+0

創建Position那麼我是否將外鍵取出來指那個位置S'而且,如果我在看一個特定的人,我可以看到他們的所有職位嗎? –

+0

是的,人不應該有一個FK來定位。職位應該有一個人。使用管理員「內聯」來查看它們。使用person.position_set.all()通過ORM訪問反向FK。閱讀文檔/玩得開心。 –

+0

非常感謝。欣賞它 –

0

要得到自己的位置類中添加的末尾:

person = models.ForeignKey(Person) 

基本上這是一個一對多的關係(一個人可以有多個位置)。您將不得不重建數據庫(使用南遷移,因爲syncdb無法從頭重新創建)來創建外鍵約束。

+0

他已經有了一個'Person'的外鍵 – Ngenator

1

你已經解決了它!

Reverse許多關係正在返回一個QuerySet,因此您使用它查詢數據庫的相同方法用於提取相關的行。

即。

# Grab a person 
some_person = Person.objects.get(pk=2) 

# Get the persons positions 
positions = some_person.position_set.filter(currenty_there=True) 

# Add a new position for this person 
some_person.position_set.add(some_new_position) 

反向設置的默認名稱爲modelname_set,如果你想要一個更友好的名稱,您可以添加related_name到現場

class Position(models.Model): 
    person = models.ForeignKey(Person, related_name="positions") 
    ... 

positions = some_person.positions.all() 
0

你是不是正確的一些人說。當您使用外鍵時,您聲明的模型與其他模型具有一對多關係。在你的情況下,PersonPosition有一對多的關係,這意味着Person可以有很多Positions,但Position只能有一個Person

可以使用RelatedManager訪問Positions一個人

要爲每個Person訪問Positions只是像做

harry = Person.objects.get(first_name="Harry", last_name="Potter") 
harry.position_set.all() 

要爲Person

harry.position_set.create(company="Hogwarts", summary="Student", ...) 

etc... 
相關問題