Problem in Deleting Model Entries having ForeignKey Constraint - django

class Client(models.Model):
client_id = models.CharField(primary_key=True, max_length=255)
name = models.CharField(max_length=255, blank=False)
class Cont(models.Model):
contid = models.CharField(max_length=255, primary_key=True)
Client = models.ForeignKey(Client, on_delete=models.PROTECT)
class ContractDailyIndent(models.Model):
id = models.CharField(max_length=255, primary_key=True)
cont = models.ForeignKey(Cont, on_delete=models.PROTECT)
class VDLContract(models.Model):
id = models.CharField(max_length=255, primary_key=True)
contractindent = models.ForeignKey(ContractDailyIndent,
on_delete=models.PROTECT)
Getting error in this line
VDLContract.objects.filter(contractindent__cont__Client__in=clients).delete()
It's giving error:
Traceback (most recent call last):
File "/home/puranjay/Documents/FeasOpt/new/fo_ftl_puranjay/mysite/empanelment/views.py", line 10432, in update_client_type
delete_client_type(user, client_type_id)
File "/home/puranjay/Documents/FeasOpt/new/fo_ftl_puranjay/mysite/empanelment/views.py", line 105, in delete_client_type
delete_indent_models(user, clients)
File "/home/puranjay/Documents/FeasOpt/new/fo_ftl_puranjay/mysite/empanelment/utility.py", line 962, in delete_indent_models
raise e
File "/home/puranjay/Documents/FeasOpt/new/fo_ftl_puranjay/mysite/empanelment/utility.py", line 941, in delete_indent_models
VDLContract.objects.filter(contractindent__cont__Client__in=clients).delete()
File "/home/puranjay/Documents/FeasOpt/env/venv/lib/python3.6/site-packages/django/db/models/query.py", line 661, in delete
collector.collect(del_query)
File "/home/puranjay/Documents/FeasOpt/env/venv/lib/python3.6/site-packages/django/db/models/deletion.py", line 222, in collect
field.remote_field.on_delete(self, field, sub_objs, self.using)
TypeError: 'NoneType' object is not callable

I tried implementing your problem on my localmachine.
Django causes this error because of foreign key constraint.This happens when your foreign key is dependent on other models, in your case VDLContract may have dependency on other model which need to be deleted first.

Related

AttributeError: 'str' object has no attribute '_meta' when attempting to use Many to Many field on self with through model - Django

Django version - 4.0.4
I am making a recipe engine website and I am trying to create a table Ingredient where each ingredient may have substitutable ingredients.
For example, ingredient "acorn squash" has the following substituable ingredients:
ingredient title: butternut squash. Conversion: 1 cup acorn squash = 1 cup butternut squash
ingredient title: pumpkin. Conversion: 1 cup acorn squash = 1 cup pumpkin
To achieve this, I have a class Ingredient and a class SubstitutableIngredient in models.py. I use a many to many field in Ingredient which uses "through" to link to the SubstitutableIngredient table, as I have extra fields such as "conversion". I use 'self' as a substitutable ingredient is still an ingredient. When attempting to makemigrations or migrate, I get the following error: AttributeError: 'str' object has no attribute '_meta' when attempting to makemigrations or migrate. Stack trace shown further below.
My code in Models.py is:
from django.db import models
# Create your models here.
class Ingredient(models.Model):
title = models.CharField(max_length=200,
unique=True) # unique field. There may only be one ingredient in the database with the same title.
# many to many field
substitutableIngredients = models.ManyToManyField(
'self',
through='SubstitutableIngredient',
through_fields=('originalIngredient', 'newIngredient'),
)
def __str__(self):
return self.title
class SubstitutableIngredient:
originalIngredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE, related_name="originalIngredient")
newIngredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE, related_name="newIngredient")
# the conversion rules between the ingredients (e.g. 1 cup = 2 cups)
conversion = models.CharField(max_length=200)
# A Cuisine has a title which is unique.
class Cuisine(models.Model):
title = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.title
# recipe class inherits from Model
class Recipe(models.Model):
# attributes
title = models.CharField(max_length=200)
# every Recipe can have many ingredients and each ingredient can have many recipes.
# relationship is modelled by the IngredientInRecipe model.
ingredients = models.ManyToManyField(
Ingredient,
through='IngredientInRecipe',
through_fields=('recipe', 'ingredient')
)
instructions = models.TextField(blank=True, null=True)
vegetarian = models.BooleanField(blank=True, null=True)
vegan = models.BooleanField(blank=True, null=True)
glutenFree = models.BooleanField(blank=True, null=True)
dairyFree = models.BooleanField(blank=True, null=True)
sourceUrl = models.CharField(max_length=200, blank=True, null=True)
image = models.CharField(max_length=200, blank=True, null=True)
cuisines = models.ManyToManyField(Cuisine, blank=True, null=True)
def __str__(self):
return self.title
# Intermediary class working between Recipe and Ingredient.
class IngredientInRecipe(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
unit = models.CharField(max_length=200)
quantity = models.FloatField()
def __str__(self):
return self.recipe.title + "," + self.ingredient.title
Strack trace:
C:\[pathname]>python manage.py makemigrations
Traceback (most recent call last):
File "C:[pathname]\manage.py", line 22, in <module>
main()
File "C:[pathname]\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
utility.execute()
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 455, in execute
self.check()
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 487, in check
all_issues = checks.run_checks(
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\checks\model_checks.py", line 36, in check_all_models
errors.extend(model.check(**kwargs))
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 1442, in check
*cls._check_fields(**kwargs),
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 1556, in _check_fields
errors.extend(field.check(from_model=cls, **kwargs))
File "C:\[pathname]\lesle\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related.py", line 1376, in check
*self._check_relationship_model(**kwargs),
File "C:\Users\[pathname]\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related.py", line 1603, in _check_relationship_model
for f in through._meta.fields:
AttributeError: 'str' object has no attribute '_meta'
I'm very confused because the following code, which is almost identical to mine, works perfectly fine.
Example code:
# Create your models here.
class Person(models.Model):
name = models.CharField(max_length=50)
# note the additional arguments here
friends = models.ManyToManyField(
'self',
# recursive relationships to self with intermediary
# through model are always defined as non-symmetrical
# symmetrical=False,
through='PersonFriend',
# this argument is required to define a custom
# through model for many to many relationship to self
# position matters: 1 - source (from), 2 - target (to)
through_fields=('person', 'friend'),
)
class PersonFriend(models.Model):
# required relationship-defining foreign keys
# (note that the order does not matter, it matters
# in 'through_fields' argument in 'friends' field of the 'Person' model)
person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="person")
friend = models.ForeignKey(Person, on_delete=models.CASCADE, related_name="friend")
# additional fields
comment = models.CharField(max_length=50)
What I've already tried:
Deleting the database and migrations files
changing to through=main.SubstituableIngredient as suggested in Django many-to-many 'str' object has no attribute '_meta' does not help

The value of 'list_display[5]' must not be a ManyToManyField

I am trying to create manytomany fields in one of the class, I am getting an error "The value of 'list_display[5]' must not be a ManyToManyField"
Need Help, Thanks in advance :)
class ShiftConfig(models.Model):
description = models.CharField(max_length=30)
start_time = models.TimeField()
end_time = models.TimeField()
def __str__(self):
return str(self.id) + ' : ' + str(self.start_time)
class FaultConfig(models.Model):
description = models.CharField(max_length=30)
message = models.ForeignKey(Message, null=True, on_delete=models.SET_NULL)
recipients = models.ForeignKey(UserGroup, null=True, on_delete=models.SET_NULL)
alert_time = models.DurationField(default=timedelta(0.0001))
repeat = models.PositiveSmallIntegerField()
escalated_fault = models.ForeignKey('self', null=True, on_delete=models.SET_NULL, blank=True)
def __str__(self):
return str(self.id) + ' : ' + str(self.description)
Here is the concerned class.
class WorkStation(models.Model):
name = models.CharField(max_length=30)
location = models.CharField(max_length=30)
department= models.ForeignKey(Department, null=True, on_delete=models.SET_NULL)
current_user=models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
allowed_fault_configs = models.ManyToManyField(FaultConfig, through='WFMembership', through_fields=('workstation', 'fault_config'))
allowed_shift_configs = models.ManyToManyField(ShiftConfig, through='WSMembership', through_fields=('workstation', 'shift_config'))
def __str__(self):
return str(self.id) + ' : ' + str(self.name)
class WFMembership(models.Model):
workstation = models.ForeignKey(WorkStation, on_delete=models.CASCADE)
fault_config = models.ForeignKey(FaultConfig, on_delete=models.CASCADE)
class WSMembership(models.Model):
workstation = models.ForeignKey(WorkStation, on_delete=models.CASCADE)
shift_config = models.ForeignKey(ShiftConfig, on_delete=models.CASCADE)
Here is the error which mentions that the field must not be ManyToManyField
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Program Files\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Program Files\Python36\lib\site-packages\channels\management\commands\runserver.py", line 69, in inner_run
self.check(display_num_errors=True)
File "C:\Program Files\Python36\lib\site-packages\django\core\management\base.py", line 441, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'andon.admin.WorkStation'>: (admin.E109) The value of 'list_display[5]' must not be a ManyToManyField.
<class 'andon.admin.WorkStation'>: (admin.E109) The value of 'list_display[6]' must not be a ManyToManyField.
System check identified 2 issues (0 silenced).
Here is the admin.py for Workstation
#admin.register(WorkStation)
class WorkStation(admin.ModelAdmin):
list_display = ('id', 'name','location','department','current_user','allowed_fault_configs', 'allowed_shift_configs')
list_display_links = ('id', 'name')
Can you post your admin.py? Specifically andon.admin.WorkStation?
Please refer to Django documentation for ManytoManyField usage in admin console.
You can write a custom function to retrieve those values from the ManyToManyField.

Django: error while trying to access ManyToMany field

I'm trying to create a twitter like application as a practice project, and following this video tutorial. I've created following models in my app.
class Profile(models.Model):
user = models.OneToOneField(to=User, on_delete=models.CASCADE)
bio = models.CharField(max_length=160, blank=True)
profile_photo = models.ImageField(blank=True, null=True)
followers = models.ManyToManyField("self", through="Relationship", related_name="follow_to",
symmetrical=False, blank=True)
class Relationship(models.Model):
user_followed = models.ForeignKey("User", related_name="followed", on_delete=models.CASCADE)
followed_by = models.ForeignKey("Profile", related_name="follower", on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now=True)
The migrations ran successfully.
After this for testing, I created two users (user1 and user2) with their respective profiles and made user2 to follow user1. Here's the code for that-
Relationship.objects.create(user_followed=user1,followed_by=user2.profile)
This relationship was successfully created. I try the following code to try to get followers of user1-
user1.profile.followers.all()
But above code is giving following errors-
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/mayank/.pyenv/versions/dwitter/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 535, in __get__
return self.related_manager_cls(instance)
File "/Users/mayank/.pyenv/versions/dwitter/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 821, in __init__
self.target_field_name = rel.field.m2m_reverse_field_name()
File "/Users/mayank/.pyenv/versions/dwitter/lib/python3.8/site-packages/django/db/models/fields/related.py", line 1554, in _get_m2m_reverse_attr
return getattr(self, cache_attr)
AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'
I tried following the method mentioned here, but it is also giving the same error. I'm not sure where have I committed a mistake. I would be thankful if someone can correct me.
Since you make an ManyToManyField to 'self' both the ForeignKeys should point to Profile:
class Relationship(models.Model):
followed = models.ForeignKey(
'Profile',
related_name='followed',
on_delete=models.CASCADE
)
followed_by = models.ForeignKey(
'Profile',
related_name='follower',
on_delete=models.CASCADE
)
timestamp = models.DateTimeField(auto_now=True)
Since now both ForeignKeys point to the same model, there is an ambiguity what the source field, and what the target field is. You resolve this by specifying this with the through_fields=… parameter [Django-doc]:
class Profile(models.Model):
user = models.OneToOneField(to=User, on_delete=models.CASCADE)
bio = models.CharField(max_length=160, blank=True)
profile_photo = models.ImageField(blank=True, null=True)
followers = models.ManyToManyField(
'self',
through='Relationship',
related_name='follow_to',
related_fields=('followed', 'followed_by')
symmetrical=False,
blank=True
)
You thus can create a follower Relation with:
Relationship.objects.create(
followed=user1.profile,
followed_by=user2.profile
)

Django giving Cannot force an update in save() with no primary key

I'm getting ValueError: Cannot force an update in save() with no primary key. while code hitting to exception and run get_or_create code. Model has it's table in database with auto incremental id field. And also this is not an update process. I can't get why Django behaving like this.
ERROR:
Traceback (most recent call last):
File "x.py", line 1980, in <module>
getattr(a, islem)()
File "x.py", line 718, in method
Slug='undefined', Status=False)
File "~/env/local/lib/python2.7/site-packages/django/db/models/manager.py", line 135, in get_or_create
return self.get_query_set().get_or_create(**kwargs)
File "~/env/local/lib/python2.7/site-packages/django/db/models/query.py", line 385, in get_or_create
obj.save(force_insert=True, using=self.db)
File ~/core/modules/xx/models.py", line 78, in save
super(Categories, self).save(args, kwargs)
File "~/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 460, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "x/env/local/lib/python2.7/site-packages/django/db/models/base.py", line 541, in save_base
raise ValueError("Cannot force an update in save() with no primary key.")
ValueError: Cannot force an update in save() with no primary key.
CODE:
try:
category = Categories.objects.get(Code=category_code)
except ObjectDoesNotExist:
category, created = Categories.objects.get_or_create(
Name='Undefined', Code='undefined',ParentCategoryID=None, OrderID=0,
Slug='undefined', Status=False)
MODEL:
class Categories(models.Model):
Name = models.CharField(max_length=155)
Code = models.CharField(max_length=255)
ParentCategoryID = models.ForeignKey('self', related_name='SubCategory', null=True, blank=True)
Level = models.IntegerField(default=0, max_length=10, editable=False)
OrderID = models.IntegerField(blank=True, max_length=10)
Slug = models.SlugField(max_length=250)
CreateDate = models.DateTimeField(auto_now_add=True)
LastUpdateDate = models.DateTimeField(auto_now=True)
Status = models.BooleanField(default=True)
def save(self, *args, **kwargs):
if self.ParentCategoryID is not None:
parent = Categories.objects.get(id=self.ParentCategoryID.id)
self.Level = parent.Level + 1
if self.OrderID <= 0:
try:
top = Categories.objects.order_by('-OrderID')[0]
self.OrderID = top.OrderID + 1
except:
self.OrderID = 1
super(Categories, self).save(args, kwargs)
You need to use the * and ** when you call super as well:
super(Categories, self).save(*args, **kwargs)
Note there are some other strange things in this code too. Primarily this line:
parent = Categories.objects.get(id=self.ParentCategoryID.id)
is doing two identical queries for no reason; self.ParentCategoryID is already the parent object. You should just do:
parent = self.ParentCategoryID
which should lead you to the conclusion that the ParentCategoryID is badly named; it contains the actual object, not the ID.
Note also that there are quite a few style violation; Python prefers lower_case_with_underscore for attribute names, and Django prefers singular model names. The related name for the foreign key should be plural, though, as it will refer to multiple category objects. So:
class Category(models.Model):
name = models.CharField(max_length=155)
code = models.CharField(max_length=255)
parent_category = models.ForeignKey('self', related_name='sub_categories', null=True, blank=True)
...

Cannot run django server after integrating database

I am having problems running my server after I try to integrate the database with the application using the "python manage.py inspectdb > /models.py" command.
This is what I have in my models.py file
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# Feel free to rename the models, but don't rename db_table values or field names.
#
# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'
# into your database.
from __future__ import unicode_literals
from django.db import models
class AuthGroup(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=80)
class Meta:
db_table = 'auth_group'
class AuthGroupPermissions(models.Model):
id = models.IntegerField(primary_key=True)
group = models.ForeignKey(AuthGroup)
permission = models.ForeignKey('AuthPermission')
class Meta:
db_table = 'auth_group_permissions'
class AuthPermission(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=50)
content_type = models.ForeignKey('DjangoContentType')
codename = models.CharField(max_length=100)
class Meta:
db_table = 'auth_permission'
class AuthUser(models.Model):
id = models.IntegerField(primary_key=True)
password = models.CharField(max_length=128)
last_login = models.DateTimeField()
is_superuser = models.BooleanField()
username = models.CharField(max_length=30)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.CharField(max_length=75)
is_staff = models.BooleanField()
is_active = models.BooleanField()
date_joined = models.DateTimeField()
class Meta:
db_table = 'auth_user'
class AuthUserGroups(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(AuthUser)
group = models.ForeignKey(AuthGroup)
class Meta:
db_table = 'auth_user_groups'
class AuthUserUserPermissions(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(AuthUser)
permission = models.ForeignKey(AuthPermission)
class Meta:
db_table = 'auth_user_user_permissions'
class DjangoContentType(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
app_label = models.CharField(max_length=100)
model = models.CharField(max_length=100)
class Meta:
db_table = 'django_content_type'
class DjangoSession(models.Model):
session_key = models.CharField(max_length=40)
session_data = models.TextField()
expire_date = models.DateTimeField()
class Meta:
db_table = 'django_session'
class DjangoSite(models.Model):
id = models.IntegerField(primary_key=True)
domain = models.CharField(max_length=100)
name = models.CharField(max_length=50)
class Meta:
db_table = 'django_site'
class DjangoUser(models.Model):
firstname = models.CharField(max_length=256)
lastname = models.CharField(max_length=256)
username = models.CharField(primary_key=True, max_length=256)
password = models.CharField(max_length=256)
class Meta:
db_table = 'django_user'
and this is the error message I get
Unhandled exception in thread started by <bound method Command.inner_run of <django.contrib.staticfiles.management.comma
nds.runserver.Command object at 0x0000000002CD1518>>
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\django\core\management\commands\runserver.py", line 92, in inner_run
self.validate(display_num_errors=True)
File "C:\Python33\lib\site-packages\django\core\management\base.py", line 280, in validate
num_errors = get_validation_errors(s, app)
File "C:\Python33\lib\site-packages\django\core\management\validation.py", line 35, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "C:\Python33\lib\site-packages\django\db\models\loading.py", line 166, in get_app_errors
self._populate()
File "C:\Python33\lib\site-packages\django\db\models\loading.py", line 72, in _populate
self.load_app(app_name, True)
File "C:\Python33\lib\site-packages\django\db\models\loading.py", line 96, in load_app
models = import_module('.models', app_name)
File "C:\Python33\lib\site-packages\django\utils\importlib.py", line 35, in import_module
__import__(name)
TypeError: source code string cannot contain null bytes
It seems I have a null variable some place but I don't know where that is coming from. I would appreciate some help.
I just had this problem myself. I finally fixed it:
open the generated model.py file in Notepad++ (or other)
copy/paste the generated code into a new file in IDLE
Save over model.py
I'm not sure why this works, but I got an encoding error trying to open the file directly in IDLE. So I copy/pasted the code, and it fixes everything.
I had the same problem using Sublime 3 as editor. It got solved if I resaved the models.py file in my app folder as 'Save with Encoding :: UTF-8'.