k44 k44 - 1 year ago 155
Python Question

Many to many relation. ORM Django

class Toy(models.Model):
name = models.CharField(max_length=20)
desc = models.TextField()

class Box(models.Model):
name = models.CharField(max_length=20)
proprietor = models.ForeignKey(User, related_name='User_Box')
toys = models.ManyToManyField(Toy, blank=True)

How to create a view that add Toy to Box?

def add_this_toy_to_box(request, toy_id):

Answer Source

You can use Django's RelatedManager:

A “related manager” is a manager used in a one-to-many or many-to-many related context. This happens in two cases:

The “other side” of a ForeignKey relation. That is:

class Reporter(models.Model):

class Article(models.Model):
    reporter = models.ForeignKey(Reporter)

In the above example, the methods below will be available on the manager reporter.article_set.

Both sides of a ManyToManyField relation:

class Topping(models.Model):

class Pizza(models.Model):
    toppings = models.ManyToManyField(Topping)

In this example, the methods below will be available both on topping.pizza_set and on pizza.toppings.

These related managers have some extra methods:

  1. To create a new object, saves it and puts it in the related object set. Returns the newly created object: create(**kwargs)

    >>> b = Toy.objects.get(id=1)
    >>> e = b.box_set.create(
    ...     name='Hi',
    ... )
    # No need to call e.save() at this point -- it's already been saved.
    # OR:
    >>> b = Toy.objects.get(id=1)
    >>> e = Box(
    ...     toy=b,
    ...     name='Hi',
    ... )
    >>> e.save(force_insert=True)
  2. To add model objects to the related object set:

    add(obj1[, obj2, ...])


    >>> t = Toy.objects.get(id=1)
    >>> b = Box.objects.get(id=234)
    >>> t.box_set.add(b) # Associates Box b with Toy t.
  3. To removes the specified model objects from the related object set:

    remove(obj1[, obj2, ...])
    >>> b = Toy.objects.get(id=1)
    >>> e = Box.objects.get(id=234)
    >>> b.box_set.remove(e) # Disassociates Entry e from Blog b.

    In order to prevent database inconsistency, this method only exists on ForeignKey objects where null=True. If the related field can't be set to None (NULL), then an object can't be removed from a relation without being added to another. In the above example, removing e from b.entry_set() is equivalent to doing e.blog = None, and because the blog ForeignKey doesn't have null=True, this is invalid.

  4. Removes all objects from the related object set: clear()

    >>> b = Toy.objects.get(id=1)
    >>> b.box_set.clear()

    Note this doesn't delete the related objects -- it just disassociates them. Just like remove(), clear() is only available on ForeignKeys where null=True.

Reference: Relevant Django doc on handling related objects

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download