my models.py
class Ingredient(models.Model):
name = models.CharField(max_length=16, unique=True)
price = models.SmallIntegerField()
def __str__(self):
return self.name
class Topping(models.Model):
name = models.CharField(max_length=32)
ingredient = models.ForeignKey(Ingredient, related_name='indole',
blank=True, null=True, default='base')
def __str__(self):
return self.nome
class Pizza(models.Model):
nome = models.CharField(max_length=32, unique=True)
toppings = models.ManyToManyField(Topping)
def __str__(self):
return self.nome
In the Admin it work! I can add topping, pizza, etc. But I want to use a script to populate.
My script
:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'recipt.settings')
import django
django.setup()
from core.models import *
def populate():
cheap = add_ingredient('Cheap', 3)
base = add_ingredient('Base', 5)
good = add_ingredient('Good', 10)
cheese = add_topping('Cheese', None)
tomato = add_topping('Tomato', None)
olive = add_topping('Olive', None)
simple = add_pizza('Simple', cheese) #just one toppings for now
complex = add_pizza('Complex', tomato)
def add_ingredient(name, price):
i = Ingredient.objects.get_or_create(name=name, price=price)[0]
i.save()
return i
def add_topping(name, ingredient):
t = Topping.objects.get_or_create(name=name, ingredient=ingredient)[0]
t.save()
return t
def add_pizza(name, toppings):
p = Pizza.objects.get_or_create(name=name, toppings=toppings)[0]
p.save()
return p
if __name__ == '__main__':
print ("Starting Core population script...")
populate()
This script work for ingredient and topping but not for Pizza.
My error
(sorry for the formatting):
Starting Core population script...
Traceback (most recent call last):
File "c:\Python34\Scripts\recipt\myvenv\lib\site-packages\django\db\mode ls\query.py", line 465, in get_or_create
return self.get(**lookup), False
File "c:\Python34\Scripts\recipt\myvenv\lib\site-packages\django\db\mode ls\query.py", line 387, in getself.model._meta.object_name
core.models.DoesNotExist: Pizza matching query does not exist.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "populate_core.py", line 437, in modulepopulate()
File "populate_core.py", line 63, in populatesimple = add_pizza('Simple', cheese)
File "populate_core.py", line 307, in add_pizzap = Pizza.objects.get_or_create(name=name, toppings=toppings)[0]
File "c:\Python34\Scripts\recipt\myvenv\lib\site-packages\django\db\mode ls\manager.py", line 122, in manager_methodreturn getattr(self.get_queryset(), name)(*args, **kwargs)
File "c:\Python34\Scripts\recipt\myvenv\lib\site-packages\django\db\mode ls\query.py", line 467, in get_or_createreturn self._create_object_from_params(lookup, params)
File "c:\Python34\Scripts\recipt\myvenv\lib\site-packages\django\db\mode ls\query.py", line 499, in _create_object_from_paramsobj = self.create(**params)
File "c:\Python34\Scripts\recipt\myvenv\lib\site-packages\django\db\mode ls\query.py", line 399, in createobj = self.model(**kwargs)
File "c:\Python34\Scripts\recipt\myvenv\lib\site-packages\django\db\mode ls\base.py", line 443, in initraise TypeError("'%s' is an invalid keyword argument for this function" % li st(kwargs)[0]) TypeError: 'toppings' is an invalid keyword argument for this function
Any help please? I read somewhere I should leave toppings blank and add later but...
When you create a database record that has a ManyToMany
field, you can't do it normally. You have to create the object, and then add things to the ManyToMany
field. Something like this.
class Author(models.Model):
name = models.CharField(max_length=100)
class Article(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
zach = Author("Zach Braff")
zach.save()
# Say Zach writes an article...
# You can't do this because the authors field could have many things in it.
a1 = Article(name="Scrubs remake coming?", authors=zach)
# Instead, you have to do this...
a1 = Article(name="Scrubs remake coming?")
a1.authors.add(zach)
a1.save()
What you might want to do is replace get_or_create()
with effectively its equivalent, like this.
p = Pizza.objects.filter(name=name, toppings=toppings)
# This is faster than `if p`
if p.exists():
return p
else:
p = Pizza.objects.create(name=name)
p.toppings.add(toppings)
p.save()
return p
I think that ought to work.