Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save eclecticmiraclecat/9f34db3ba76b7db26154ac5be842503f to your computer and use it in GitHub Desktop.
Save eclecticmiraclecat/9f34db3ba76b7db26154ac5be842503f to your computer and use it in GitHub Desktop.

many to one

  • one customer ordering many product
# models.py
class Customer(models.Model):
  name = models.CharField(max_length=20)

class Product(models.Model):
  product = models.CharField(max_length=20)
  customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
>>> from cbvApp.models import Customer, Product
>>> c = Customer(name='alice')
>>> c.save()
>>> c.product_set.create(product='milk')
<Product: Product object (1)>
>>> c.product_set.create(product='eggs')
<Product: Product object (2)>
Customer
+----+-------+
| id | name  |
+----+-------+
|  1 | alice |
+----+-------+

Product
+----+---------+-------------+
| id | product | customer_id |
+----+---------+-------------+
|  1 | milk    |           1 |
|  2 | eggs    |           1 |
+----+---------+-------------+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment