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.
Related
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.
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.
In my case I need design my model in array of fields expected.
{field 1: string, field 2: [""], field 3: [""] }
So far I designed my model like following:
class Collaborator(models.Model):
name = models.CharField(max_length=50, blank=True, null = True, )
class Responsibility(models.Model):
name = models.CharField(max_length=50, blank=True, null = True, )
class Class1(models.Model):
field 1 = models.CharField(max_length=50, blank=True, null = True, )
field 2 = models.ManyToManyField(Responsibility, related_name='res_cards', blank=True,null=True )
field 3 = models.ManyToManyField(Collaborator, related_name='col_cards', blank=True, null=True )
So I am expecting for to get all fields in an array rather than define new model
If you are using SQLite as your database, there is no alternative for ManyToManyField.
However, if you are using (or if you switch to) PostgreSQL as your database, you'll be able to use ArrayField.
You can use it like this:
field_1 = ArrayField(
models.CharField(max_length=50, blank=True)
)
P.S. I assume you aren't really going to name your fields field 1 etc., but if you do, don't use spaces, use underscores instead, so field_1, etc.
There is lots of information on how to use Postgres instead of SQLite, for instance this link would be a good start.
However, in most cases I would still recommend using a ManyToManyField, because it'll enable you to easily query on shared relationships between two objects, and prevent duplicate data as well.
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.
total novice here. Trying to work with sqlalchemy but have hit a problem.
class Establishment(Base):
__tablename__ = 'establishments'
estaID = Column(String(5), primary_key=True)
typeID = Column(String(2), ForeignKey('types.typeID'))
type = relationship("Type", backref=backref('estabs', order_by=estaID))
def __init__(self, id):
self.estaID = id
try:
session = Session()
existsEsta = session.query(Establishment).filter(Establishment.estaID == self.estaID).one()
session.close()
self.typeID = existsEsta.typeID
except NoResultFound, e:
session = Session()
print "Establishment: ", self.estaID, "does not yet exist."
type = Type(raw_input("Please enter type: "))
self.typeID = type.gettypeID()
print "Adding establishment", self.estaID, self.typeID
session.add(self)
session.commit
For some reason, the session.add(self) is not adding the record to the db. I'm having particular difficult figuring out what's going on because this "Establishment" class is modeled after another class (identical algorithm, different variable names) which works just fine.
Thoughts as to where I'm going wrong here?
Thanks in advance.
Try session.commit() instead of session.commit.