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.
Related
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
I have two apps 'user' and 'game' and here is my user/models.py:
from django.db import models
from django.db.models.fields import related
from django.contrib.auth.models import AbstractBaseUser , User,
AbstractUser , PermissionsMixin
from .managers import CustomUserManager
from game.models import Game
class User(AbstractBaseUser,PermissionsMixin):
username = models.CharField(max_length=150,
unique=True, blank=True , null=True,)
email = models.EmailField( blank=True , null=True , unique=True)
password = models.CharField(max_length=100, null=True , blank=True)
objects = CustomUserManager()
class Meta:
db_table = 'user'
class Team(models.Model):
name = models.CharField(max_length=40, unique=True)
players = models.ManyToManyField(User,
related_name="players")
game = models.ManyToManyField(Game)
is_verfied = models.BooleanField(default=False)
class Meta:
db_table = 'team'
and here is my game/models.py:
from django.db import models
from user.models import User, Team
from leaga.settings import AUTH_USER_MODEL
class Game(models.Model):
name = models.CharField(max_length=50)
is_multiplayer = models.BooleanField(default=False)
class Event(models.Model):
title = models.CharField(max_length=100)
start_date = models.DateTimeField()
end_date = models.DateTimeField()
class Tournament(models.Model):
title = models.CharField(max_length=50)
is_team = models.BooleanField(default=False)
price = models.PositiveIntegerField()
info = models.TextField(max_length=1000)
user = models.ManyToManyField(AUTH_USER_MODEL,
related_name='tounament_user')
team = models.ManyToManyField(Team, related_name='team')
game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='tournament_game')
event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='tournament_event')
# some other code and classes here but unnecessary to mention
.
.
.
.
when i run :
python manage.py makemigrations user
this is the console log:
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 "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 357, in execute
django.setup()
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate
app_config.import_models()
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/site-packages/django/apps/config.py", line 211, in import_models
self.models_module = import_module(models_module_name)
File "/Users/amir/Desktop/leaga/.venv/lib/python3.7/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/amir/Desktop/leaga/leaga/user/models.py", line 6, in <module>
from game.models import Game
File "/Users/amir/Desktop/leaga/leaga/game/models.py", line 3, in <module>
from user.models import Team
ImportError: cannot import name 'Team' from 'user.models' (/Users/amir/Desktop/leaga/leaga/user/models.py)
I tried to delete all .pyc files from my project
also, drop the entire database and create again(i know it's probably not the point but I got angry and I dropped the entire database and recreate it
File "/Users/amir/Desktop/leaga/leaga/user/models.py", line 6, in
from game.models import Game
File "/Users/amir/Desktop/leaga/leaga/game/models.py", line 3, in
from user.models import Team
ImportError: cannot import name 'Team' from 'user.models' (/Users/amir/Desktop/leaga/leaga/user/models.py)
From the message we can see that this is due to circular imports.
user/models.py tries to import the Game model from game/models.py, and game/models.py tries to import the Team model from user/models.py.
One solution is to remove:
from game.models import Game
From user/models.py, and change:
game = models.ManyToManyField(Game)
To:
game = models.ManyToManyField('game.Game')
You might want to read: ForeignKey and ManyToManyField.
Relevant part copied here:
If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:
I was working on a project where a user can upload multiple images. everything is work fine but Now I want to create a new folder for every user with the custom name with date time just because people cannot overwrite there own image.
Like my every file is upload inside
assets/uploads/
but I want to create a new folder for each user by there user id and upload there image inside that folder with date time rename.
|->assets|
|
|->uploads
|
|->1 (folder created by user id)
|
|->2 (folder created by user id)
here is my model.py code
class Uqdetail(models.Model):
uq_main_id = models.IntegerField(blank=True, null=True)
company_id = models.IntegerField(blank=True, null=True)
item_name = models.CharField(max_length=255, blank=True, null=True)
item_slug = models.CharField(max_length=255, blank=True, null=True)
item_image = models.FileField(upload_to='uploads/')
# ##### item_image = models.FileField(upload_to='uploads/'+UrgentQueryUserFolder+'/') (I try this by getting error)
quantity = models.IntegerField(blank=True, null=True)
unit = models.CharField(max_length=45, blank=True, null=True)
moq = models.FloatField(blank=True, null=True)
lead_time = models.IntegerField(blank=True, null=True)
payment = models.CharField(max_length=255, blank=True, null=True)
created_by = models.IntegerField(blank=True, null=True, default=0)
modified_by = models.IntegerField(blank=True, null=True, default=0)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
deleted = models.IntegerField(blank=True, null=True)
I was trying to write a function inside my model to get a current user id for creating user folder by passing that id but not helping to get error
def UrgentQueryUserFolder(self):
user_id = self.id
return user_id
Here is the error
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/home/an2/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/home/an2/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/home/an2/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception
raise _exception[0](_exception[1]).with_traceback(_exception[2])
File "/home/an2/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/home/an2/.local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/an2/.local/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate
app_config.import_models()
File "/home/an2/.local/lib/python3.6/site-packages/django/apps/config.py", line 211, 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/an2/office/s2s/s2s/urgentQuery/models.py", line 24, in <module>
class Uqdetail(models.Model):
File "/home/an2/office/s2s/s2s/urgentQuery/models.py", line 29, in Uqdetail
item_image = models.FileField(upload_to='uploads/urgentQuery/'+UrgentQueryUserFolder+'/')
NameError: name 'UrgentQueryUserFolder' is not defined
Traceback (most recent call last):
File "/home/an2/.local/lib/python3.6/site-packages/django/apps/registry.py", line 155, in get_app_config
return self.app_configs[app_label]
KeyError: 'admin'
How can I create a new folder for each upload image user and also rename that image with new daytime and save that database to?
my model
class BaseModel(models.Model):
CreatedDate = models.DateTimeField(auto_now_add=True, verbose_name="Oluşturulma Tarihi")
ModifiedDate = models.DateTimeField(auto_now=True, verbose_name="Son Güncellenme tarihi")
Isdeleted = models.BooleanField(verbose_name="Silindi", default=False)
class Case(BaseModel):
CaseNumber = models.CharField(max_length=14)
Customer = models.ForeignKey(Customer)
Title = models.ForeignKey(CaseTitle)
CaseCategory = models.ForeignKey(CaseCategory, verbose_name="Kategori")
Priority = models.ForeignKey(CasePriority)
Status = models.ForeignKey(CaseStatus)
Detail = models.TextField()
Group = models.ForeignKey(Group)
User = models.ForeignKey(User,related_name='User' )
AssignedUser = models.ForeignKey(User,related_name='AssignedUser')
CloseDetail = models.TextField blank=True)
i just want to give 2 foreign key this my model but error is
Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/related.py", line 796, in __init__
to._meta.model_name AttributeError: 'ForeignKey' object has no attribute '_meta'
During handling of the above exception, another exception occurred:
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 338, in execute
django.setup()
File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models()
File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/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 "/code/Case/models.py", line 91, in <module>
class Case(BaseModel):
File "/code/Case/models.py", line 101, in Case
AssignedUser = models.ForeignKey(User,related_name='AssignedUser')
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/related.py", line 802, in __init__
RECURSIVE_RELATIONSHIP_CONSTANT, AssertionError: ForeignKey(<django.db.models.fields.related.ForeignKey>) is invalid.
First parameter to ForeignKey must be either a model, a model name, or the string 'self'
You're redefining User The relevant section of Django code this is bombing on is an isinstance(to, str) which means User is not a model but it's also not a string (it's a ForeignKey).
If you're using Django's User model or a customized variant the correct way to obtain a reference independently is to use django.contrib.auth.get_user_model(). e.g.:
from django.contrib.auth import get_user_model
User = get_user_model()
class MyModel(models.Model):
user = models.ForeignKey(User)
In Python it's convention to lowercase names unless they are classes.
Does it work if you only implement one relationship to the model User? The error message:
First parameter to ForeignKey must be either a model, a model name, or the string 'self'
lets me assume, that you're not passing the actual class of the User model. How do you obtain it?
Also, from looking at the fields of BaseModel I suppose, it could be an abstract base model:
class BaseModel(models.Model):
class Meta:
abstract = True
CreatedDate = models.DateTimeField(auto_now_add=True, verbose_name="Oluşturulma Tarihi")
...
See here for more information: https://godjango.com/blog/django-abstract-base-class-model-inheritance/
You should be following the python conventions on how to use uppercase, lowercase, otherwise the interpreter is going to refer to wrong variables:
Classes are the only things that should be camel-case (class User, class CaseTitle).
Your class properties (instance variables) should be lowercase with underscores: case_number, user, assigned_user, etc...
When you write User = ForeignKey(User) you're actually redefining the User variable, so in the next line AssignedUser = ForeignKey(User), User isn't the User model class anymore. If I write it out, I get:
AssignedUser = models.ForeignKey( # User
models.ForeignKey( # User
models.ForeignKey( # User etc...
...
Change the field name User to anything you want. It conflicts that's why you get the error.
class Case(BaseModel):
....
user = models.ForeignKey(User,related_name='user' )
assigned_user = models.ForeignKey(User,related_name='assigned_user')
Read all topics at StackOverflow and internet - no luck.
# admindivisions.models
class Countries(models.Model):
osm_id = models.IntegerField(db_index=True, null=True)
status = models.IntegerField()
population = models.IntegerField(null=True)
iso3166_1 = models.CharField(max_length=2, blank=True)
iso3166_1_a2 = models.CharField(max_length=2, blank=True)
iso3166_1_a3 = models.CharField(max_length=3, blank=True)
class Meta:
db_table = 'admindivisions_countries'
verbose_name = 'Country'
verbose_name_plural = 'Countries'
class CountriesTranslations(models.Model):
common_name = models.CharField(max_length=81, blank=True, db_index=True)
formal_name = models.CharField(max_length=100, blank=True)
country = models.ForeignKey(Countries, on_delete=models.CASCADE, verbose_name='Details of Country')
lang_group = models.ForeignKey(LanguagesGroups, on_delete=models.CASCADE, verbose_name='Language of Country',
null=True)
class Meta:
db_table = 'admindivisions_countries_translations'
verbose_name = 'Country Translation'
verbose_name_plural = 'Countries Translations'
# profiles.models
from admindivisions.models import CountriesTranslations, Countries
class AbstractProfile(models.Model):
COUNTRY_CHOICES = ()
if (Languages.objects.model._meta.db_table in connection.introspection.table_names()):
# Just for test - This executes without any errors
CountriesTranslations.objects.filter(common_name="USA")
for country in Countries.objects.filter(status=1).exclude(iso3166_1='', iso3166_1_a2=''):
# Just for test - Also executes ok
CountriesTranslations.objects.get(common_name="USA")
# Makes problem (seems to be because of FK)
country_name = CountriesTranslations.objects.get(country=country)
COUNTRY_CHOICES += ((country.id, country_name),)
country = models.ForeignKey(Countries, verbose_name=_('country'), choices=COUNTRY_CHOICES, blank=True)
title = models.CharField(_('title'), max_length=30)
info = models.TextField(_('information'), max_length=500, blank=True)
class Meta:
abstract = True
Traceback:
Traceback (most recent call last):
File "./manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute
django.setup()
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/apps/config.py", line 199, in import_models
self.models_module = import_module(models_module_name)
File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "/home/antonio/www/sportland/sportland/src/profiles/models.py", line 76, in <module>
class AbstractProfile(models.Model):
File "/home/antonio/www/sportland/sportland/src/profiles/models.py", line 109, in AbstractProfile
country_name = CountriesTranslations.objects.get(country=country)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/query.py", line 376, in get
clone = self.filter(*args, **kwargs)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/query.py", line 796, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/query.py", line 814, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1227, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1253, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1133, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1019, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/sql/query.py", line 1308, in names_to_path
if field.is_relation and not field.related_model:
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/db/models/fields/related.py", line 111, in related_model
apps.check_models_ready()
File "/home/antonio/www/sportland/lib/python3.5/site-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
This happens if I want to execute any manage.pys command.
Coming from few tests above I can guess the problem is due to ForeignKey. How to fix it?
Django 1.10
You mustn't do any logic like that at class level. Obviously you can't query the models until they are all fully loaded.
I don't understand what you are trying to do there, but you should move it into a method.