2012-04-11 1 views
8

Я строю Джанго tastypie апи, и у меня есть проблема с добавлением элементов в 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, мне все равно нужно указать всех людей на картинке. Конечно, я мог бы просто сгенерировать URL-адрес /api/picture/:id/add_people, и я мог бы справиться со своей проблемой. Проблема в том, что он не чувствует себя чистым.

Другим решением было бы генерировать /api/picture/:id/people конечную точку, и я мог бы сделать GET, POST, PUT, как это новый ресурс, но я не знаю, как осуществить это и кажется странным, чтобы создать новых людей по этому ресурсу.

Любые мысли?

+0

я как-то задал тот же вопрос http://stackoverflow.com/questions/8613522/how-to-put-product-to-cart-via-tasytpie-api – seb

+1

Sorry @seb я искал для моей проблемы и я не нашел тебя вопросом. Если вы хотите, я могу удалить свой вопрос, но, пожалуйста, измените свое имя, так как «Как поместить продукт в корзину через tasytpie API?» просто слишком специфичен –

+0

@seb - ваш вопрос все еще открыт, я не вижу, что вы приняли ответ! – Mutant

ответ

4

Я реализовал это, переопределив функцию save_m2m ресурса API. Вот пример использования ваших моделей.

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)