2012-06-13 101 views
7

我的模型:訪問多對多「通過」關係領域中的表單集

class End_User(models.Model): 
    location = models.ForeignKey(Location) 
    first_name = models.CharField(max_length=70, blank=True, null=True) 
    email_address = models.CharField(max_length=70, blank=True, null=True) 

class Phone_Client(models.Model): 
    end_user = models.ManyToManyField(End_User) 
... 
    extensions = models.CharField(max_length=20) 

class Line(models.Model): 
    phone_client = models.ManyToManyField(Phone_Client, through='Phone_Line') 
    .... 
    voicemail = models.BooleanField(default=False) 

class Phone_Line(models.Model): 
    phone_client = models.ForeignKey(Phone_Client) 
    line = models.ForeignKey(Line) 
    line_index = models.IntegerField() 

所以基本上一個最終用戶可以有多個電話,一個電話就可以有很多線,通過Phone_line有關。

我的頁面需要所有這些對象都是可編輯的,並且新實例爲Phone_Clients和Line創建了運行時,它們都在同一頁面中。目前,我正在爲Phone_Client和Lines創建一個簡單的End_User模型表單和modelformset_factory對象。由於電話可以有多條線路,因此phone_formset中的每個電話表單都可以有一個線路formset對象。我目前正在做這樣的事情

end_user = End_User.objects.get(pk=user_id) 
user_form = End_UserForm(instance=end_user) 

Phone_ClientFormSet = modelformset_factory(Phone_Client,form=PartialPhone_ClientForm, extra=0, can_delete=True) 

phone_clients_formset = Phone_ClientFormSet(queryset=end_user.phone_client_set.all(), prefix='phone_client') 

all_lines = modelformset_factory(Line, form=PartialLineForm, extra=0, can_delete=True) 

phone_clients = end_user.phone_client_set.all() 

client_lines_formsets = {} 
for phone in phone_clients: 
    client_lines_formsets[phone.id] = all_lines(queryset=phone.line_set.all(), prefix='phone_client_'+str(phone.id)) 

我使用此列表來顯示屬於使用formset的模板中的phone_client的行。

我有以下問題,對模型

  1. 我可以使用inline_formset工廠來處理多對多的關係,包含通過階級?如果是這樣,我怎麼做的Phone_Client,Line和Phone_Line通過關係?

  2. 我需要顯示給定的手機,線路組合的line_index,我該如何在模板中做到這一點?我已經看過
    How do I access the properties of a many-to-many "through" table from a django template? 我不想只顯示,但綁定值的手機,行組合,如果可能的線或電話formset,如果用戶更改索引,我可以將其保存在數據中同時發佈formset數據。

我是新來的django,所以任何幫助真的很感激。 謝謝!

回答

14

正如您可能知道的那樣,您無法使用內嵌窗體組編輯多對多關係。但是,您可以編輯直通模型。因此,對於您的在線表單集,你只需要通過模型到模型設置爲,例如:

inlineformset_factory(Phone_Client, Line.phone_client.through) 

line_index竟然會被內聯表單上的可見字段,所以你真的沒有做任何事情。如果某人更改了索引,那麼當內聯表單被保存時它將被保存,就像其餘的字段一樣。

+0

感謝您的回覆。我會試試這個! – akotian

+0

我試過了,它適用於我。 但是有一個問題,我將不得不單獨處理Line formset和上面的內聯formset吧? – akotian

+0

我的意思是一個頁面可以有多個電話,可以有多個線路,所以我在模板中處理這個邏輯。同樣,我將不得不使用右邊的模板來顯示line_index旁邊的行? – akotian