I have been making changes to my models and adding new ones (many times). But now when I ran python3 manage.py makemigrations, I suddenly got this error:
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
I deleted all migrations and the sqlite database file to start from scratch, but I get the same error again. All my models are registered in admin.py.
I'm using Django 2.0.3.
Can someone help me with this?
Here is the full traceback:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute
django.setup()
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/mnt/c/git/project3/orders/models.py", line 85, in <module>
class PizzaOrder(models.Model):
File "/mnt/c/git/project3/orders/models.py", line 90, in PizzaOrder
p = Pizza.objects.get(pk=pizza_id)
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/query.py", line 394, in get
clone = self.filter(*args, **kwargs)
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/query.py", line 836, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/query.py", line 854, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1253, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1277, in _add_q
split_subq=split_subq,
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1153, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1015, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1355, in names_to_path
if field.is_relation and not field.related_model:
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/fields/related.py", line 94, in related_model
apps.check_models_ready()
File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/apps/registry.py", line 132, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
Here is my full models.py:
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
from django.contrib.auth.models import User
from django.conf import settings
LARGE = 'L'
SMALL = 'S'
SIZE_CHOICES = ( (SMALL, 'Small'), (LARGE, 'Large'),)
class Dish(models.Model):
PIZZA = 'PIZZA'
SUB = 'SUB'
PASTASALAD = 'PASTASALAD'
PLATTER = 'PLATTER'
TYPE_CHOICES = ( (PIZZA, 'Pizza'), (SUB, 'Sub'), (PASTASALAD, 'PastaSalad'), (PLATTER, 'Platter') )
name = models.CharField(max_length=64, blank=True) # blank makes name optional
type = models.CharField(max_length=64, choices=TYPE_CHOICES, blank=True)
size = models.CharField(max_length=1, choices=SIZE_CHOICES, default=SMALL, blank=True)
price = models.DecimalField(max_digits=6, decimal_places=2, default=None)
def __str__(self):
return f"{self.name} {self.size} - Price: ${self.price}"
class Order(models.Model):
order_id = models.AutoField(primary_key=True)
customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="active_customer")#can ditch rel name
time = models.DateTimeField()
total = models.DecimalField(max_digits=7, decimal_places=2)
def __str__(self):
return f"Order {self.order_id}, customer: {self.customer}. Total: ${self.total} - {self.time}"
class PastaSalad(Dish):
dish = models.OneToOneField(Dish, on_delete=models.CASCADE, related_name="dish_id_pastasalad", parent_link=True)
def __str__(self):
return f"{self.name}, price: ${self.price}"
class Topping(models.Model):
name = models.CharField(max_length=64, primary_key=True)
def __str__(self):
return f"{self.name}"
class Pizza(Dish):
dish = models.OneToOneField(Dish, on_delete=models.CASCADE, related_name="dish_id_pizza", parent_link=True)
REGULAR = 'REGULAR'
SICILIAN = 'SICILIAN'
STYLE_CHOICES = ( (REGULAR, 'Regular'), (SICILIAN, 'Sicilian'),)
style = models.CharField(max_length=64, choices=STYLE_CHOICES, default=REGULAR)
topping_count = models.IntegerField(default=0, validators=[MaxValueValidator(5), MinValueValidator(0)])
def __str__(self):
return f"{self.size} {self.style} pizza with {self.topping_count} toppings: ${self.price}"
class Sub(Dish):
dish = models.OneToOneField(Dish, on_delete=models.CASCADE, related_name="dish_id_sub", parent_link=True)
def __str__(self):
return f"{self.name}, Size: ${self.szie}, Price: ${self.price}"
class PizzaOrder(models.Model):
pizza_id = models.ForeignKey(Pizza, related_name="pizza_id", on_delete=models.DO_NOTHING)
order_id = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="pizza_order_id")
p = Pizza.objects.get(pk=pizza_id)
toppings = []
for i in range (p.topping_count):
str = "topping_"+(i+1)
toppings.append(str)
for t in toppings:
t = models.ForeignKey(Topping)
def __str__(self):
return f"Pizza Order: {self.order_id}, Size & Style: {p.size} {p.style}, Toppings: {p.topping_count}"
class Platter(Dish):
dish = models.OneToOneField(Dish, on_delete=models.CASCADE, related_name="dish_id_platter", parent_link=True)
def __str__(self):
return f"{self.name} price: ${self.price}, size ${self.size}"
class PlatterOrder(models.Model):
order_id = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="platter_to_order_id")
platter_id = models.ForeignKey(Platter, related_name="platter_id")
def __str__(self):
p = Platter.objects.get(pk=platter_id)
return f"Platter Order: {self.order_id}, {p.name}, size: {p.size}"
class SubOrder(models.Model):
sub_id = models.ForeignKey(Sub, related_name="sub_id")
order_id = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="sub_to_order_id")
extra_count = models.IntegerField(default=0, validators=[MaxValueValidator(4), MinValueValidator(0)])
MUSHIES = 'M'
PEPPERS = 'P'
ONIONS = 'O'
XTRCHEESE = 'C'
EXTRA_CHOICES = ((MUSHIES, 'Mushrooms'), (PEPPERS, 'Peppers'), (ONIONS, 'Onions'), (XTRCHEESE, 'Extra Cheese'),)
extra_1 = models.CharField(max_length=1, choices=EXTRA_CHOICES, blank=True)
extra_2 = models.CharField(max_length=1, choices=EXTRA_CHOICES, blank=True)
extra_3 = models.CharField(max_length=1, choices=EXTRA_CHOICES, blank=True)
extra_4 = models.CharField(max_length=1, choices=EXTRA_CHOICES, blank=True)
def __str__(self):
s = Sub.objects.get(pk=sub_id) # LET'S SEE IF THIS WORKS
extras = []
for i in range(extra_count):
str = "extra_"+i
extras.append(str)
return f"Sub Order: {self.order_id}, {s.name}, size: {s.size}. {self.extra_count} Extras: {extras}"
class PastaSaladOrder(models.Model):
order_id = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="pastasalad_to_order_id")
pastasalad_id = models.ForeignKey(PastaSalad, related_name="pastasalad_id")
def __str__(self):
ps = PastaSalad.objects.get(pk=pastasalad_id) # LET'S SEE IF THIS WORKS
return f"Pasta/Salad Order: {self.order_id}, {ps.name}"
Your issue is here in PizzaOrder:
p = Pizza.objects.get(pk=pizza_id)
toppings = []
for i in range (p.topping_count):
str = "topping_"+(i+1)
toppings.append(str)
for t in toppings:
t = models.ForeignKey(Topping)
As the traceback suggests, your model hasn't loaded but you're trying to refer to it with .objects.get(). I think you want to link the Pizzas to the PizzaOrder, if so then you need to set this as a ForeignKey (or other relationship) in the Pizza model. Removing this segment of code should work (although you do have some missing on_delete fields in your ForeignKeys).
The structure of your models seems quite complicated, I think you can do away with the food models and foodOrder models as they probably don't add anything. You could have four models, each with their own choice fields:
Order > Platter > Dish > Topping/Extra
Dish could have a choice field which refers to pizza, pasta, etc. have a price and link to toppings/extras as needed.
adding
import django
django.setup()
works for me
bug i had the dir structure like
settings
|
|- base.py ( common settings for all stage)
|- dev.py
|- local.py
|- production.py
so for that i have to add above setup thing in end of all three files (dev, local, prod)
so its working fine now
Related
I am trying to create a seeding script using Faker. In my models.ContentCategory, the parent_category has a recursive foreign key. However, I could not find a way to translate this into my faker script. I am really open to all kinds of helps!
here is my models.py:
class ContentCategory(models.Model):
name = models.CharField(blank=False, null=False, max_length=100)
description = models.CharField(blank=False, null=False, max_length=100)
parent_category = models.ForeignKey(
"self", on_delete=models.DO_NOTHING, null=True, blank=True, parent_link=True,
)
# down here should be fixed after creating the sections model
parent_section = models.ForeignKey(
Sections, on_delete=models.CASCADE, blank=True, null=True
)
def __str__(self):
return self.name
class Meta:
verbose_name = "content category"
verbose_name_plural = "Content Categories"
and here is the handler snippet:
#seeding Content Category
for _ in range(4):
name = fake.word(ext_word_list=None)
description = fake.sentence(nb_words=15, variable_nb_words=True, ext_word_list=None)
#creating ids and parent ids
cid = random.randint(1,4)
# creating key for Sections
ptid = random.randint(1,14)
ContentCategory.objects.create(
name=name, description=description, parent_category=cid, parent_section=ptid
)
check_content_categories = ContentCategory.objects.count().all()
here is the full error log:
python manage.py seed
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/home/myyagis/meethaq/be/be/api/management/commands/seed.py", line 104, in handle
ContentCategory.objects.create(
File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/query.py", line 420, in create
obj = self.model(**kwargs)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/base.py", line 483, in __init__
_setattr(self, field.name, rel_obj)
File "/home/myyagis/.local/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 206, in __set__
raise ValueError(
ValueError: Cannot assign "1": "ContentCategory.parent_category" must be a "ContentCategory" instance.
Thank you in advance!
Solved:
In the model, the foreign key tables were already accepting blank=True, null=True, hence, I discarded these from the seeder script, it automatically filled the db with the null values.
Better solutions for non-nullable fields :
Model.objects.order_by('?').first() confirmed using.
recursive foreign key accepts the model's own name as the Model name.
example for the model UserCategory:
for _ in range(200):
category = UserCategory.objects.order_by('?').first()
email = fake.unique.ascii_free_email()
password = fake.unique.word(ext_word_list=None)
gender =fake.api_gender()
first_name = fake.unique.first_name()
last_name = fake.unique.last_name()
phone_number = fake.country_calling_code() + fake.phone_number()
birthday = fake.unique.date_of_birth()
I have the following Models
from django.db import models
class League(models.Model):
league_id = models.IntegerField()
country = models.ForeignKey('Country', on_delete = models.CASCADE)
name = models.CharField(max_length = 50)
logo = models.CharField(max_length = 250)
season = models.IntegerField()
season_start = models.DateField()
season_end = models.DateField()
standings = models.BooleanField(default= False)
class Country(models.Model):
country = models.CharField(max_length = 20, primary_key=True)
country_id = models.IntegerField()
I created custom management command to get data from API then extract disered data from API responce and create object of model based on this data. My custom management command code
from django.core.management.base import BaseCommand, CommandError
from data.models import League, Country
import requests
import json
def extracting_league():
response = requests.get("https://api-football-v1.p.rapidapi.com/leagues", headers={"X-RapidAPI-Key": "rRVyARf9ESmshWSiNIkYcTr0jp1nQh2JjsnNGNlcEYXM1XI"})
league = json.loads(response.text)
return league
parsed_league = extracting_league()
print(parsed_league)
def pars():
leagues = parsed_league['api']['leagues']
for id in parsed_league['api']['leagues']:
lg_id = leagues[id]["league_id"]
lg_name = leagues[id]["name"]
lg_country = Country.objects.get_or_create(country = leagues[id]["country"])
lg_logo = leagues[id]["logo"]
lg_season = leagues[id]["season"]
One_league = League.objects.create(league_id = lg_id, country = lg_country, name = lg_name, logo = lg_logo, season = leagues[id]["season"], season_start = leagues[id]["season_start"], season_end = leagues[id]["season_end"], standings = leagues[id]["standings"])
One_league.save()
print(One_league)
class Command(BaseCommand):
def handle(self, **options):
extracting_league()
pars()
When i run script with python manage.py 'custom management commmand' i see in console the following error notifications
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
__init__.py", line 381, in execute_from_command_line
utility.execute()
File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "D:\Python\my_projects\forecast\lib\site-packages\django\core\management\
base.py", line 353, in execute
output = self.handle(*args, **options)
File "D:\Python\my_projects\forecast\project\forecasting\data\management\comma
nds\extract_league.py", line 70, in handle
pars()
File "D:\Python\my_projects\forecast\project\forecasting\data\management\comma
nds\extract_league.py", line 25, in pars
One_league = League.objects.create(league_id = lg_id, country = lg_country,
name = lg_name, logo = lg_logo, season = leagues[id]["season"], season_start = l
eagues[id]["season_start"], season_end = leagues[id]["season_end"], standings =
leagues[id]["standings"])
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\manage
r.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\query.
py", line 411, in create
obj = self.model(**kwargs)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\base.p
y", line 467, in __init__
_setattr(self, field.name, rel_obj)
File "D:\Python\my_projects\forecast\lib\site-packages\django\db\models\fields
\related_descriptors.py", line 210, in __set__
self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "(<Country: Country object (Turkey)>, False)": "League
.country" must be a "Country" instance.
I can not to understand the following traceback message
ValueError: Cannot assign "(<Country: Country object (Turkey)>, False)": "League
.country" must be a "Country" instance.
It seems like in my Country model table is not country by Turkey name but when i look at table in PGadmin i have Turkey country in the Country table. Any suggestions
The django method get_or_create returns a tuple of (object, created), so you can use next solution:
lg_country, _ = Country.objects.get_or_create(country = leagues[id]["country"])
I have two apps appointments and clinic in my project myappointments.
I have defined a model in appointments/models.py:
class Clinicdb(models.Model):
clinicid = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=60, unique=True)
label = models.SlugField(max_length=25, unique=True)
email = models.EmailField(max_length=50, default='')
mobile = models.CharField(max_length=15, default='')
alternate = models.CharField(max_length=15, default='', blank=True)
about = models.CharField(max_length=250, blank=True)
state = models.CharField(max_length=25)
city = models.CharField(max_length=35)
locality = models.CharField(max_length=35)
pincode = models.IntegerField(default=0)
address = models.TextField(max_length=80, default='', blank=True)
website = models.URLField(blank=True)
logo = models.ForeignKey(ProfilePic, blank=True, null=True, on_delete=models.CASCADE)
class Meta:
unique_together = ["name", "mobile", "email"]
def __str__(self):
return self.name
In clinic/models.py, I have:
from appointments.models import Clinicdb
class Album (models.Model):
name = models.CharField(max_length=255)
photo = models.FileField(upload_to="data/media/%Y/%m/%d")
clinicid = models.ForeignKey(Clinicdb, blank=True,
null=True, on_delete=models.CASCADE)
def __str__(self):
return self.photo
However when running makemigrations (and runserver) I get:
joel#hp:~/myappointments$ python3 manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/joel/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute
django.setup()
File "/home/joel/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/joel/.local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/home/joel/.local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/joel/myappointments/appointments/models.py", line 4, in <module>
from clinic.models import Pic, ProfilePic
File "/home/joel/myappointments/clinic/models.py", line 3, in <module>
from appointments.models import Clinicdb
ImportError: cannot import name 'Clinicdb'
You made a cyclic import, if we look at the bottom of the traceback, we see that:
File "/home/joel/myappointments/appointments/models.py", line 4, in <module>
from clinic.models import Pic, ProfilePic
File "/home/joel/myappointments/clinic/models.py", line 3, in <module>
from appointments.models import Clinicdb
So that means that clinic/models.py needs to import appointments/models.py first, but vice versa also holds, hence we can not import this. It comes down to the "chicken and the egg" problem: for an egg, we need a chicken, but for a chicken we need an agg, which results in a logical problem.
What you thus need to do is remove the import, and use a qualified name in a string, like:
# clinic/models.py
# NO import
class Album (models.Model):
name = models.CharField(max_length=255)
photo = models.FileField(upload_to="data/media/%Y/%m/%d")
clinicid = models.ForeignKey('appointment.Clinicdb', blank=True,
null=True, on_delete=models.CASCADE)
def __str__(self):
return self.photo
Django will automatically load the INSTALLED_APPS and replace the qualified string with a reference to the model (in fact one of the reasons of this functionality is solve the circular reference problem).
Note: normally ForeignKeys (and related relation fields) do not end with an id, or _id suffix, so I suggest that you rename clinicid to clinic. This makes sense since a some_album.clinic is not an id of a Clinic, but a Clinic object. Django will automatically add an extra field named clinic_id that stores the id.
I have a Django app that has CustomUser. My model looks something like
class CustomUser(AbstractBaseUser):
def get_short_name(self):
pass
def get_full_name(self):
pass
firstName = models.CharField(max_length=300)
middleName = models.CharField(max_length=300, blank=True)
lastName = models.CharField(max_length=300, blank=True)
username = models.CharField(unique=True, max_length=50)
businessName = models.CharField(max_length=500, default=None)
mobileNumber = models.CharField(max_length=20)
contactNumber = models.CharField(max_length=20)
addressLine1 = models.CharField(max_length=300)
addressLine2 = models.CharField(max_length=300)
city = models.CharField(max_length=300)
state = models.CharField(max_length=300)
role = models.CharField(max_length=20)
email_id = models.CharField(max_length=300, unique=True)
aadharNumber = models.BigIntegerField(default=0)
panNumber = models.CharField(max_length=20, default=None)
registrationDate = models.BigIntegerField(default=0)
bankDetail = models.ManyToManyField('BankDetail', related_name="bankDetail")
dateCreated = models.DateTimeField(auto_now_add=True)
dateModified = models.DateTimeField(auto_now=True)
objects = AccountManager()
USERNAME_FIELD = 'email_id'
REQUIRED_FIELDS = ['username']
I was following the example in this blog https://afropolymath.svbtle.com/authentication-using-django-rest-framework to implement User authentication.
I get the following error when I run makemigrations
I did look at a few solutions on StackOverflow but those don't seem to solve my problem.
Django error message "Add a related_name argument to the definition"
AlterField on auto generated _ptr field in migration causes FieldError
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 177, in handle
migration_name=self.migration_name,
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/autodetector.py", line 47, in changes
changes = self._detect_changes(convert_apps, graph)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/autodetector.py", line 133, in _detect_changes
self.old_apps = self.from_state.concrete_apps
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/state.py", line 222, in concrete_apps
self.apps = StateApps(self.real_apps, self.models, ignore_swappable=True)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/state.py", line 288, in __init__
self.render_multiple(list(models.values()) + self.real_models)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/state.py", line 323, in render_multiple
model.render(self)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/state.py", line 626, in render
body,
File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 259, in __new__
base.__name__,
django.core.exceptions.FieldError: Auto-generated field 'user_ptr' in class 'CustomUser' for parent_link to base class 'User' clashes with declared field of the same name.
customer ID<django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x106341a58>
What do I need to do to get rid of this error and proceed with a successful migration?
Delete your migrations .
Then run makemigrations command.
Please I need help with this code:
>>> t = Transaction.objects.filter(paid=True)
>>> t
[<Transaction: ac0e95f6cd994cc39807d986f7a10d4d>, <Transaction: 7067361871fd459f
aa144988ffa22c7c>, <Transaction: 134e5ab4b0a74b5a985ff53e31370818>, <Transaction
: ef451670efad4995bff755621c162807>]
>>> t[0]
<Transaction: ac0e95f6cd994cc39807d986f7a10d4d>
>>> t[0].branch_name
<Branch: WAREHOUSE ROAD>
>>> Transaction.objects.get(branch_name='WAREHOUSE ROAD')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\mana
ger.py", line 132, in get
return self.get_query_set().get(*args, **kwargs)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 344, in get
num = len(clone)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 82, in __len__
self._result_cache = list(self.iterator())
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 273, in iterator
for row in compiler.results_iter():
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\sql\
compiler.py", line 680, in results_iter
for rows in self.execute_sql(MULTI):
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\sql\
compiler.py", line 735, in execute_sql
cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\backends\ut
il.py", line 34, in execute
return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\backends\my
sql\base.py", line 86, in execute
return self.cursor.execute(query, args)
File "build\bdist.win32\egg\MySQLdb\cursors.py", line 176, in execute
if not self._defer_warnings: self._warning_check()
File "build\bdist.win32\egg\MySQLdb\cursors.py", line 92, in _warning_check
warn(w[-1], self.Warning, 3)
Warning: Truncated incorrect DOUBLE value: 'WAREHOUSE ROAD'
Here is Branch and Transaction models:
class Branch(models.Model):
""" Branch """
bid = models.AutoField(primary_key=True)
institution = models.CharField(max_length=50)
branchcode = models.CharField(max_length=50)
name_branch = models.CharField(max_length=255)
name_branch_short = models.CharField(max_length=50)
address_1 = models.CharField(max_length=100)
name_city = models.CharField(max_length=50)
name_state = models.CharField(max_length=50)
sector = models.CharField(max_length=50)
class Meta:
db_table = u'branch'
def __unicode__(self):
return self.name_branch
class Transaction(models.Model):
"""Gateway transactions"""
id = models.AutoField(primary_key=True)
tpin = UUIDField(max_length=32, blank=True, editable=False,\
help_text='Transaction Payment Identification Number')
user_id = models.IntegerField(help_text='The user who made the transaction')
amount = models.DecimalField(max_digits=14, decimal_places=2, \
help_text='Transaction amount')
identifier = models.CharField(max_length=100, blank=True, \
help_text='A unique identifier provided by the student')
institution = models.ForeignKey(Institution, related_name='transactions')
financial_institution = models.ForeignKey('FinancialInstitution', blank=True, null=True, related_name='transactions', help_text='The financial institution this transaction was updated in')
branch_name = models.ForeignKey(Branch, blank=True, null=True, related_name='transactions', \
help_text='The bank branch where this transaction is originating from')
paid = models.BooleanField(default=False)
teller_no = models.CharField(max_length=20, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
audit_log = AuditLog(exclude=['created', 'updated', ])
def __unicode__(self):
return self.tpin
def natural_key(self):
""" A natural key is a tuple of values that can be used to uniquely identify an object
instance without using the primary key value.
"""
return self.tpin
I tried to serialize Transaction like this:
>>> from django.core import serializers
>>> serializers.serialize('csv', t)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\serialize
rs\__init__.py", line 91, in serialize
s.serialize(queryset, **options)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\serialize
rs\base.py", line 48, in serialize
self.handle_fk_field(obj, field)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\core\serialize
rs\python.py", line 48, in handle_fk_field
related = getattr(obj, field.name)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\fiel
ds\related.py", line 315, in __get__
rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 349, in get
% self.model._meta.object_name)
DoesNotExist: Branch matching query does not exist.
I don't understanding why get is returning DoesNotExists on Branch. I showed an example above which shows that Branch has a record in Transaction.
Looping through t I get a result, but then followed by DoesNotExist: Branch matching query does not exist
>>> for i in t:
... i.branch_name
...
<Branch: WAREHOUSE ROAD>
Traceback (most recent call last):
File "<console>", line 2, in <module>
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\fiel
ds\related.py", line 315, in __get__
rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)
File "C:\Python27\lib\site-packages\django-1.3-py2.7.egg\django\db\models\quer
y.py", line 349, in get
% self.model._meta.object_name)
DoesNotExist: Branch matching query does not exist.
Please help. Thanks
This query:
Transaction.objects.get(branch_name='WAREHOUSE ROAD')
filters for branch_name which is a ForeignKey field. To query on that name, you should use two underscores:
Transaction.objects.get(branch_name__name_branch='WAREHOUSE ROAD')
Not the most convenient names for your fields...