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):
Django automatically creates reverse relations on ManyToManyFields, so you can do:
You can use Django's
RelatedManager
:These related managers have some extra methods:
To create a new object, saves it and puts it in the related object set. Returns the newly created object: create(**kwargs)
To add model objects to the related object set:
Example:
To removes the specified model objects from the related object set:
Removes all objects from the related object set: clear()
Reference: Relevant Django doc on handling related objects