Django/MySQL time datatype - python

I´m using Django to import from an existing mysql database thats already created and is used by somebody else. Im using:
python manage.py inspectdb > models.py
And the class from my model in question is the following:
class Funciones(models.Model):
idfuncion = models.IntegerField(primary_key=True)
idpelicula = models.ForeignKey(Peliculas, db_column='idpelicula')
idcine = models.ForeignKey(Cines, db_column='idcine')
hora = models.TextField() # This field type is a guess.
tipo_3d = models.IntegerField(null=True, db_column=u'3d', blank=True) # Field renamed
xd = models.IntegerField(null=True, blank=True)
gtmax = models.IntegerField(null=True, blank=True)
vip = models.IntegerField(null=True, blank=True)
idioma = models.CharField(max_length=33)
idciudad = models.ForeignKey(Ciudades, db_column='idciudad')
class Meta:
db_table = u'funciones'
Now this attribute:
hora = models.TextField() # This field type is a guess
corresponds to a time dataType in MYSQL.
Now, since I cant change the dataType in MYSQL because somebody else has already created a number of queries to the database from another app, I would like to know what would be the appropriate corresponding django datatype that I should use in my django model.
I was thinking DateTimeField but then I should have to somehow truncate the date part before writing to the database.
Any ideas?
Thanks
Edit:
As pointed out by Pedro:
Django actually has a TimeField, why not use that? – Pedro Romano

You could use the Timedelta object to represent "time elapsed" using this https://djangosnippets.org/snippets/1060/

Related

Python Django always passes id 1 on ForeignKey with to_field

I'm new to Django and trying to create a small application that shows scanned data from virtual machines that are inserted in a table named HostsFixDataScans.
To access the scanned data in HostsFixDataScans via the Hosts model, I defined a ForeignKey with to_field.
But unfortunately, the data returned by the linked HostsFixDataScans are wrong.
I checked the SQL statements and when requesting the HostsFixDataScans table, not the id of the Host is used, but always 1.
My domain = models.ForeignKey(Domains, on_delete=models.CASCADE) definition which does not use to_field works correctly.
I'm pretty sure, I have a misunderstanding of the definition of this relationship.
Maybe you could give me some hints how to solve the problem?
Many thanks in advance!
Here are the shortened definitions of the models:
class Os(models.Model):
operatingsystem = models.CharField(max_length=32)
lsbdistcodename = models.CharField(max_length=32)
lsbdistrelease = models.CharField(max_length=32, db_collation='ascii_bin')
lsbmajdistrelease = models.IntegerField()
remarks = models.CharField(max_length=256, blank=True, null=True)
class HostsFixDataScans(models.Model):
host_id = models.PositiveIntegerField(primary_key=True, unique=True)
scan_id = models.PositiveIntegerField()
os = models.ForeignKey(Os, on_delete=models.CASCADE)
class Hosts(models.Model):
hostname = models.CharField(max_length=256)
domain = models.ForeignKey(Domains, on_delete=models.CASCADE)
is_virtual = models.PositiveIntegerField(blank=True, null=True)
os = models.ForeignKey(HostsFixDataScans, to_field='host_id', on_delete=models.CASCADE)
Sorry folks,
I made a really stupid mistake by connecting the field os_id with the field host_id on the other table.
I now added a field last_fix_data_scan_id to the Hosts table which has to be filled with every scan of a machine now.
But doing it this way I can now request the Hosts by connecting this new field with the scan_id of HostsFixDataScans.

Converting IntegerField to ForeignKey from recovered database in Django

I'm working with a MySQL database that I connected to my django project (using python manage.py inspectdb > app/models.py) but it's not reading the relationships correctly. The ForeignKeys are IntegerFields so I cannot use the handy Django ORM lookup. Here's an example:
class ChileStudents(models.Model):
""" simplified version of the model """
otec = models.IntegerField(blank=True, null=True) # Here's the issue
# More stuff goes here
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = True
db_table = 'chile_students'
class Otecs(models.Model):
""" Also a simplified version """
name = models.CharField(max_length=45, blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = True
db_table = 'otecs'
As shown in the example above, the IntegerField points to the OTEC id, this is a simple one-to-many relationship. I tried converting the field into a ForeignKey like this:
otec = models.ForeignKey('Otecs', on_delete=models.SET_NULL,blank=True, null=True, db_column="otec_id")
But when migrating it just sets the column otec_id to NULL.
Is there any way I can "convert" the field into a ForeingKey?
You can specify that the name of the database column is otec with db_column='otec':
class ChileStudents(models.Model):
otec = models.ForeignKey(db_column='otec', blank=True, null=True)
# More stuff goes here
updated_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'chile_students'
But since the table already exists, you can not make it managed = True, since then Django will try to create the table at the database side, create/remove columns, etc. Since here the table already exists, you can not let Django handle that, since then it will aim to create a table that already exists.

How to insert data into a relational one to one table in django?

I have a UserProfile table which is in relation with the default Django User table. Here's how it looks.
class UserProfile(models.Model):
user = user.OneToOneField(User, on_delete=models.CASCADE)
section = models.CharField(max_length=255, blank=True)
year = models.IntegerField(null=True, blank=True)
course = models.CharField(max_length=255, blank=True)
qrcode = models.CharField(max_length=255, blank=True)
present = models.BooleanField(default=False)
I am trying to insert the data into the UserProfile table using the Django Shell.
from users.models import UserProfile
a = UserProfile(qrcode="hello")
a.save()
This is how I have always known to insert data into tables, it has always worked. BUT when i try to do this in UserProfile model. I get this exception. NOT NULL constraint failed: users_userprofile.user_id. Which in turn is caused by the following exception Error in formatting: RelatedObjectDoesNotExist: UserProfile has no user.
I somewhat understand that I somehow need to supply a user instance. But I am clueless as to how. Can someone please help me.
Firstly you need to create User.
u1 = User(username='user1')
u1.save()
Create a UserProfile. Pass the ID of the “parent” object as this object’s ID:
v1 = UserProfile(user=u1, ....)
v1.save()
refer this
You need to create your User first
user = User.objects.create(username='user')
and then you can do:
user_profile = UserProfile.objects.create(user=user, ...)

Django models foreign key not recognizing 'QueryString' BaseObject

I am currently working on a Django 1.5.2 project within a Docker instance that speaks with a mysql database in a separate Docker instance. I am trying to create a Many to Many relationship between two tables by creating a middle table that contains two foreign keys that point to the two tables that need connecting. The problem arises when I run python manage.py syncdb and it spits out the following error to the terminal: NameError: name 'QueryString' is not defined. QueryString is clearly defined in my models.
Here are my Models...
class Tag(models.Model):
name = models.CharField(max_length=100)
class QueryStringTab(models.Model):
tag = models.ForeignKey(Tag, related_name='querystringtab')
querystring = models.ForeignKey(QueryString, related_name='querystringtab')
class QueryString(BaseObject):
"""
Query string holds an SQL statement and query properties for execution
"""
server_id = models.IntegerField()
schema = models.CharField(max_length=255, blank=True)
query = models.CharField(max_length=60000)
variables = models.TextField(blank=True)
created_by = models.ForeignKey(User, related_name='queries_created')
updated_by = models.ForeignKey(User, related_name='queries_last_edited')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField()
touched_by = models.CharField(max_length=1000)
config = models.TextField(blank=True)
runs_started = models.IntegerField(default=0)
runs_completed = models.IntegerField(default=0)
runs_completed_duration = models.IntegerField(default=0) # total number of seconds spent running this query to completion
formats = "pretty_html html json prettyjson csv excel tableau".split()
Noteworthy points...
1) It is recognizing the Tag model just fine.
2) Could it have something to do with the fact that QueryString is a BaseObject
3) It is successfully creating the Tag table in the mysql database
Can anyone find anything obvious that I am doing wrong?
The declaration of QueryStringTab is before the one for QueryStringTab; so when Python evaluates the first, it has not yet seen any definition for the second and therefore reports a NameError.
Django allows you to use a string target than a class object in cases like this:
querystring = models.ForeignKey('QueryString', related_name='querystringtab')
Or, you could simply move the definition of QueryStringTab to the end.

Datetime field on Django to store the date of insertion of row?

I'm new to Django. I'm starting a new App and I'm currently on the Models.
I need to store the date of the insertion of the line and when the line suffer from an UPDATE I need to store that date too.
My models.py
from django.db import models
class Directorio(models.Model):
n_site = models.CharField(max_length=60)
url = models.CharField(max_length=200)
user_db_ins = models.CharField(max_lenght=50)
user_db_upd = models.CharField(max_lenght=50)
user_system_ins = models.CharField(max_lenght=50)
user_system_upd = models.CharField(max_lenght=50)
date_inserted =
date_last_update =
How can I define the "date_inserted" and the "date_last_update"? I usually use a trigger to do this.
Can someone give me a clue on how to do it in the Django way?
Best Regards,
Documented in django here.
date_inserted = models.DateTimeField(auto_now_add=True)
date_last_update = models.DateTimeField(auto_now=True)

Categories