2012-04-11 83 views
8

我要建一個Django tastypie API,而我在ManyToMany關係Tastypie,在許多添加元素一對多的關係

添加元素

例, models.py問題

class Picture(models.db): 
    """ A picture of people""" 
    people = models.ManyToManyField(Person, related_name='pictures', 
     help_text="The people in this picture", 
    ) 

class Person(models.db): 
    """ A model to represet a person """ 
    name = models.CharField(max_length=200, 
     help_text="The name of this person", 
    ) 

資源:

class PictureResource(ModelResource): 
    """ API Resource for the Picture model """ 
    people = fields.ToManyField(PersonResource, 'people', null=True, 
     related_name="pictures", help_text="The people in this picture", 
    ) 
class PersonResource(ModelResource): 
    """ API Resource for the Person model """ 
    pictures = fields.ToManyField(PictureResource, 'pictures', null=True, 
     related_name="people", help_text="The pictures were this person appears", 
    ) 

我的問題是,我想有一個add_person終點在我的圖片資源。 如果我使用PUT,那麼我需要指定圖片中的所有數據。 如果我使用PATCH,我仍然需要指定圖片中的所有人。 當然,我可以簡單地生成​​網址,在那裏我可以處理我的問題。問題在於它感覺不乾淨。

另一種解決方案是產生/api/picture/:id/people終點,在那裏我可以做GETPOSTPUT,就像是一個新的資源,但我不知道如何實現這一點,我覺得奇怪,創造新的人在這個資源下。

有什麼想法?

+0

我莫名其妙地問我搜索我的問題同樣的問題http://stackoverflow.com/questions/8613522/how-to-put-product-to-cart-via-tasytpie-api – seb 2012-04-12 00:51:24

+1

對不起@seb我沒有發現你的問題。如果您願意,我可以刪除我的問題,但請更改您的名稱,因爲「如何通過tasytpie API將產品放入購物車?」太具體了 – 2012-04-12 11:15:38

+0

@seb - 你的問題仍然存在,我沒有看到你接受了答案! – Mutant 2012-11-29 05:03:51

回答

4

我通過覆蓋API資源的save_m2m函數來實現此目的。這裏是一個使用你的模型的例子。

def save_m2m(self, bundle): 
    for field_name, field_object in self.fields.items(): 
     if not getattr(field_object, 'is_m2m', False): 
      continue 

     if not field_object.attribute: 
      continue 

     if field_object.readonly: 
      continue 

     # Get the manager. 
     related_mngr = getattr(bundle.obj, field_object.attribute) 
      # This is code commented out from the original function 
      # that would clear out the existing related "Person" objects 
      #if hasattr(related_mngr, 'clear'): 
      # Clear it out, just to be safe. 
      #related_mngr.clear() 

     related_objs = [] 

     for related_bundle in bundle.data[field_name]: 
      # See if this person already exists in the database 
      try: 
       person = Person.objects.get(name=related_bundle.obj.name) 
      # If it doesn't exist, then save and use the object TastyPie 
      # has already prepared for creation 
      except Person.DoesNotExist: 
       person = related_bundle.obj 
       person.save() 

      related_objs.append(person) 

     related_mngr.add(*related_objs)