When attempting to loaddata - get error problem installing fixture - mysql

I am trying to load data from a db.json file I created (Sqlite db was the source). The original database is Sqlite, and I am try to migrate to Mysql.
Everything works fine under Sqlite. I get the following error:
django.db.utils.OperationalError: Problem installing fixture '/home/balh/blah/db.json': Could not load trackx_site.Segment(pk=1): (1054, "Unknown column 'program_id' in 'field list'")
It seems like the Mysql tables do not have the foreign key or something?.... The models look like this:
class Program(models.Model):
air_date = models.DateField(default="0000/00/00")
air_time = models.TimeField(default="00:00:00")
service = models.CharField(max_length=10)
block_time = models.TimeField(default="00:00:00")
block_time_delta = models.DurationField(default=timedelta)
running_time = models.TimeField(default="00:00:00",blank=True)
running_time_delta = models.DurationField(default=timedelta)
remaining_time =
models.TimeField(default="00:00:00",blank=True)
remaining_time_delta = models.DurationField(default=timedelta)
title = models.CharField(max_length=190)
locked_flag = models.BooleanField(default=False)
locked_expiration = models.DateTimeField(null=True,default=None,blank=True)
deleted_flag = models.BooleanField(default=False)
library = models.CharField(null=True,max_length=190,blank=True)
mc = models.CharField(max_length=64)
producer = models.CharField(max_length=64)
editor = models.CharField(max_length=64)
remarks = models.TextField(null=True,blank=True)
audit_time = models.DateTimeField(auto_now=True)
audit_user = models.CharField(null=True,max_length=32)
class Segment(models.Model):
class Meta:
ordering = ['sequence_number']
program = models.ForeignKey(Program,
on_delete=models.CASCADE,
related_name='segments', # link to Program
)
sequence_number = models.DecimalField(decimal_places=2,max_digits=6,default="0.00")
title = models.CharField(max_length=190, blank=True)
bridge_flag = models.BooleanField(default=False)
seg_length_time = models.TimeField()
seg_length_time_delta = models.DurationField(default=timedelta)
seg_run_time = models.TimeField(default="00:00:00",blank=True)
seg_run_time_delta = models.DurationField(default=timedelta)
seg_remaining_time = models.TimeField(default="00:00:00",blank=True)
seg_remaining_time_delta = models.DurationField(default=timedelta)
author = models.CharField(max_length=64,null=True,default=None,blank=True)
voice = models.CharField(max_length=64,null=True,default=None,blank=True)
library = models.CharField(max_length=190)
summary = models.TextField()
audit_time = models.DateTimeField(auto_now=True)
audit_user = models.CharField(null=True,max_length=32)
I also get a error when I attempt to run the server with the Mysql db settings. It will not allow me to add a record into the model and gives me an error complaining about program_id. I dont have anything named program_id that I am aware of.. (I looks through all the code).
It works fine when I run with Sqlite db settings. Adds programs and segments just fine.
Don't know what's wrong here. Any idea what I am doing wrong?

I figured out that my mysql database was not migrating correctly. Part of the problem was it was trying to do all the migrations, but since it was the inital build of the new database I did not need to have all the migrations (and somehow something was happening correctly in there). Removed all of the migrations, did initial makemigrations and migrate, and my Foreign Key was created correctly, no more problems.

Related

SQLALCHEMY CONNECTION TWO DATABASE PROBLEM

Hello I have little problem,So need Help to connect two tables in database. I used ORM in python and I know how to connect it in main.py file.But I decided to make one file per table,so when i want to use foreign key it say's error. Here is the code which i used for connection two tables:
engine = create_engine('mysql+pymysql://root:#localhost/popis?charset=utf8mb4', echo=False)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class Stanovnik(Base):
__tablename__ = "stanovnik"
id = Column(Integer, primary_key=True)
ime = Column(String(20))
prezime = Column(String(50))
ratni_staz = Column(Integer)
godine = Column(Integer)
broj_clanova=Column(Integer)
sifra_adrese = Column(Integer,ForeignKey(adresa.sifra_adrese))
sifra_zene = Column(Integer,ForeignKey(zena.sifra_zene))
sifra_ostali = Column(Integer,ForeignKey(ostali.sifra_ostali))
Base.metadata.create_all(engine)
I tried every method for sql but one thing is missing I think.

Error creating tables in MySQL using peewee and FastAPI

I have below basic code where I am trying to create tables in food_delivery database using peewee ORM. I am receiving error as below:
AttributeError: 'str' object has no attribute 'safe_create_index'
My Code below:
DATABASE = 'food_delivery'
db = MySQLDatabase(
host='localhost',
user='my_user',
password='****',
database=DATABASE
)
class BaseModel(Model):
class Meta:
database = DATABASE
class Customer(BaseModel):
city = CharField()
customer = AutoField(column_name='customer_id')
email = CharField(column_name='email_id',unique=True)
first_name = CharField()
landmark = CharField()
last_name = CharField()
password = CharField()
phone_no = CharField(max_length=10)
pincode = IntegerField()
state = CharField()
class Meta:
table_name = 'customer'
database = DATABASE
def create_tables():
with db:
db.create_tables([Customer])
create_tables()
Can someone suggest what might be wrong with code?
Thanks!
I kept looking for issue and found that I had a logical syntax misplacement basically. Instead of database name under all the table definition in META, I actually had to pass connection instance of database instead of database name. But I wonder how inappropriate the thrown error is and its kind of impossible to fi seeing the error details. This requires much improvement by library maintainers.

Django: Can't add field to custom user model

So, I've got a well running Django 3 app with a custom user model running on a MySQl db. I've been doing makemigrations and migrate successfully for months. Today I tried to add a field to my custom User Model called Account. The second I add a field to that model, the dev server attempts to process the change and crashes with this error:
django.db.utils.OperationalError: (1054, "Unknown column 'account_account.lifetimeuser' in 'field list'")
Doesn't matter the type of the field or the name.
The base exception is:
MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'account_account.lifetimeuser' in 'field list'")
Understand that this is NOT at runtime. It's right after I change the model and stop typing. Or in this case uncomment the lifetimeuser field (BTW, this is for testing only. I know I have an is_lifetime_user. That's the real field that was added sometime ago.
Also note that this is ONLY with the Account model. Every other model in the file works as expected. Add, remove, edit: no problem as long as the syntax is correct.
Since the error happens immediately, I can't makemigrations or migrate. I know my DB is in sync everywhere else.
Can anyone give me a hint as to what is going on here? Is there some DB setting I'm missing?
Thanks!
Here's the model in case that helps.
class Account(AbstractBaseUser):
id = models.UUIDField(primary_key=True, default=None, editable=False)
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True, db_index=True)
date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True)
last_login = models.DateTimeField(verbose_name="last login", auto_now=True)
access_level = models.IntegerField(default=1)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
is_freeuser = models.BooleanField(default=False)
is_10kuser = models.BooleanField(default=False)
is_100kuser = models.BooleanField(default=False)
is_lifetimeuser = models.BooleanField(default=False)
#lifetimeuser = models.BooleanField(default=False)
force_pw_change = models.BooleanField(default=False)
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=60)
profile = models.OneToOneField(UserProfile, on_delete=models.CASCADE, null=True, blank=True, db_index=True)
class Meta:
ordering = ['-date_joined']
# this is the field the user will use to login
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name']
# tell the account what AcctManager to use
objects = MyAccountManager()
A couple updates:
I went through the settings and commented out each line of middleware to see what happened when I uncomment the test field in the account model. No change.
Also, I experimented with models in the same model.py file and the test server notices the change and says reloading, and reloads successfully. It's only for the account model that this fails. Account model also says reloading but fails. Very strange.

saving an instance of a model with auto_now_add in Django returns error message Column 'xxx' cannot be null

I must be doing something very wrong or this error doesn't make any sense to me. I have an object Location:
class Location(models.Model):
class Meta:
db_table = 'location'
location_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=200)
state = models.CharField(max_length=200)
country = models.CharField(max_length=200)
apt_number = models.CharField(max_length=200, null=True, blank=True)
street_address = models.CharField(max_length=200)
city = models.CharField(max_length=200)
zip_code = models.IntegerField()
created = DateTimeField(auto_now_add=True)
here this is my code for inserting a new or updating an existing location record:
class LocationList(generics.ListCreateAPIView):
queryset = Location.objects.all()
serializer_class = LocationSerializer
def post(self, request, *args, **kwargs):
location_dict = request.data
if 'location_id' not in location_dict:
okStatus = status.HTTP_201_CREATED
else:
okStatus = status.HTTP_200_OK
location = Location(**location_dict)
location.save()
return Response(LocationSerializer(location).data, status=okStatus)
Inserts work fine, but everytime an update happens, I get the error "Column 'created' cannot be null". My online research seems to point me to the fact that this was a bug which has been long fixed. I expect the update to pass since the 'created' field was set to auto_now_add, which means Django should set that field once upon insert and leave it on any subsequent update. I do not know why Django is trying to set that column to null or any other value on update, because I expect Django to not update the column at all. I am using MySQL as database.
I think that your problem is in the " created column " try this steps :-
1) add null=True inside the created column
2) run :$ python"select version" manage.py makemigrations "appName or keep it empty"
3) run :$ python"V" manage.py sqlmegrate "aapName" " file version" >
check the file version in the app directory type it like this "0001"
4) run :$ python"V" manage.py migrate "appName"
after these steps ur db should be updated, last step is to remove (null=True from created column ) and start project.

Getting blank statement in django model charfield with mysql

I just migrated my django application from sqlite3 to mysql 5.1.41. I have a charfield in a model defined like this:
class HostData(models.Model):
Host = models.CharField(max_length=50, null=True)
HostStatus = models.CharField(max_length=200, null=True)
Alarm = models.BooleanField()
Everything works the same except HostStatus, which usually returns a string like "Up, waiting". In mysql, however, it is blank. I created my table with character set to utf-8. What am I doing wrong? Thanks in advance.
I can't see anything wrong with that model code.
How have you migrated your data over to MySQL? When you enter data via the django admin, does it enter data into the db?
If a view is entering this data, can you post the view code.
The issue was the way I was assigning the value to the model. I dont know why it worked well in sqlite, but it was bad coding anyways. This is what I was doing:
myarray = stdout_ssh
myobject = test.object.get(id=3)
myobject.Host = stdout_ssh[0]
myobject.HostStatus = status
status = stdout_ssh[1]
myobject.Alarm = False
myobject.save()
I changed this to:
myarray = stdout_ssh
myobject = test.object.get(id=3)
myobject.Host = stdout_ssh[0]
myobject.HostStatus = stdout_ssh[1]
myobject.Alarm = False
myobject.save()
And everything was ok.