| 377 | Here are some examples of :class:`~django.db.models.ManyToManyField` uses:: |
| 378 | |
| 379 | >>> mozzarella = Topping.objects.create(name="Mozzarella") |
| 380 | >>> tomato = Topping.objects.create(name="Tomato") |
| 381 | >>> salami = Topping.objects.create(name="Salami") |
| 382 | >>> diavola = Pizza.objects.create(name="Diavola") |
| 383 | |
| 384 | >>> diavola.toppings = [tomato, mozzarella] |
| 385 | >>> diavola.toppings.add(salami) |
| 386 | >>> diavola.toppings.all() |
| 387 | [<Topping: Tomato>, <Topping: Mozzarella>, <Topping: Salami>] |
| 388 | >>> margherita = Pizza.objects.create(name="Margherita") |
| 389 | # Add is also possible with primary key values |
| 390 | >>> margherita.toppings = [tomato.id, mozzarella.id] |
| 391 | >>> mozzarella.pizza_set.all() |
| 392 | [<Pizza: Diavola>, <Pizza: Margherita>] |
| 393 | |
| 394 | # Queries (from both ends of the relation) |
| 395 | >>> Pizza.objects.filter(toppings__name="Tomato") |
| 396 | [<Pizza: Diavola>, <Pizza: Margherita>] |
| 397 | >>> Pizza.objects.filter(toppings__in=[tomato, mozzarella]) |
| 398 | [<Pizza: Diavola>, <Pizza: Margherita>, <Pizza: Diavola>, <Pizza: Margherita>] |
| 399 | >>> Pizza.objects.filter(toppings__in=[tomato, mozzarella]).distinct() |
| 400 | [<Pizza: Diavola>, <Pizza: Margherita>] |
| 401 | >>> Topping.objects.filter(pizza=margherita) |
| 402 | [<Topping: Mozzarella>, <Topping: Tomato>] |
| 403 | >>> Pizza.objects.exclude(toppings=salami) |
| 404 | [<Pizza: Margherita>] |
| 405 | |
| 406 | # Removing |
| 407 | >>> margherita.toppings.remove(mozzarella) |
| 408 | >>> margherita.toppings.all() |
| 409 | [<Topping: Tomato>] |
| 410 | >>> salami.pizza_set.clear() |
| 411 | >>> diavola.toppings.all() |
| 412 | [<Topping: Tomato>, <Topping: Mozzarella>] |
| 413 | # Assigning an empty list is equivalent to clear() |
| 414 | >>> diavola.toppings = [] |
| 415 | >>> diavola.toppings.all() |
| 416 | [] |
| 417 | |