2010-05-05 66 views
2

我正在尋找一種方法來序列化與它的所有關係的整個對象。我似乎現在只能從序列化程序中獲得主鍵。Django,獲取完全序列化的對象。從很多到很多關係的所有屬性

這是我的模型:

class Action(models.Model): 
    name = models.CharField('Action Name', max_length=250, unique=True) 
    message = models.TextField('Message', blank=True, null=True) 
    subject = models.CharField('Subject', max_length=40, null=True) 
    recipient = models.ManyToManyField('Recipient', blank=True, null=True) 

    def __str__(self): 
      return unicode(self.name).encode('utf-8') 

    def __unicode__(self): 
      return unicode(self.name) 

class Recipient(models.Model): 
    address = models.EmailField('Address', max_length=75, unique=True) 
    businessHours = models.BooleanField('Business Hours Only', default=False) 

    def __str__(self): 
      return unicode(self.address).encode('utf-8') 

    def __unicode__(self): 
      return unicode(self.address) 

我這裏跑串行:

all = serializers.serialize('xml', list(Action.objects.select_related().all())) 

,如果我跑打印我得到的輸出列表只爲收件人字段的主鍵。

<field type="CharField" name="subject">On The Road Productions</field> 
<field to="sla.recipient" name="recipient" rel="ManyToManyRel"> 
<object pk="29"></object> 
</field></object> 
<object pk="11" model="sla.action"> 
<field type="CharField" name="name">On The Road Productions</field> 
<field type="TextField" name="message"> 

我還需要所有相關收件人的所有屬性。任何想法我怎麼能得到這個?

編輯 - 我發現這片

我發現了這片在xml_serializer.py,但我不知道如何修改它。

def handle_m2m_field(self, obj, field): 
    """ 
    Called to handle a ManyToManyField. Related objects are only 
    serialized as references to the object's PK (i.e. the related *data* 
    is not dumped, just the relation). 
    """ 
    if field.creates_table: 
     self._start_relational_field(field) 
     for relobj in getattr(obj, field.name).iterator(): 
      self.xml.addQuickElement("object", attrs={"pk" : smart_unicode(relobj._get_pk_val())}) 
     self.xml.endElement("field") 
+0

你可以得到相關模型的查詢集並將它們序列化? – 2010-05-05 19:13:18

+0

看起來不像是維護對象之間的關係。 – Ryan 2010-05-05 19:42:45

回答

0

建議看看django活塞內部。

用django-piston這樣做並沒有問題,代碼是非常可讀的。所以潛入。