django-modeltranslation become a already exists field in translatable - django

I'm using django-modeltranslation to translate models in my app. I've a model wich I've sync with the db with migrate command. Also I've a lot of records for that model.
class Home(models.Model):
description = models.TextField()
Of course, at this point, I can retrieve description field from db
h = Home.objects.first()
h.description # --> "This home is near to..."
Now, I want to become the description field translatable using django-modeltranslation. I've follow de guide, I've registered the model for translation in the translation.py file, Finally I've executed makemigrations and migrate commands. This added to my db, in the home table, the fields description_en and description_es, as my availabe languajes are en and es, the former is the default.
At this point i need to populate the description_en field wich is the default for any query, I tried
Home.objects.all().update(description_en=F('description'))
but it doesn't work because when it tries to access to the description field it in fact is trying to access to description_en, and it is empty:
h = Home.objects.first()
h.description # --> '' Empty?!!!
I've check if the data still in the db and they are!
My question is: if description data still in db, and h.description retrieve me in fact h.description_en, How can I populate description_en for all data in description field?

reading this django-modelstranslation fallback original field value, I realized of existence of management command that is shipped with modeltranslation and it populate the default lang: python manage.py update_translation_fields

Related

Dynamic Model in Django from fields data in another model

I am working on a project where I have 2 models model
class Customer(models.Model):
name = models.CharField(...)
...
class CustomerProperty(models.Model):
name = models.CharField(...)
type = models.CharField(...)
code = models.CharField(...)
The CustomerProperty table has rows inside based on a parquet file (created at database init, not changed later on). For column in the parquet file, CustomerProperty has a row with column name from parquet as name in the table.
Now for some other purpose, I need to copy over all the data in the parquet file inside the db. So, for each row in the CustomerProperty table, this new table will have a column (plus one column for foreign key to Customer) so I can run filters based on property values. This will also be copied over at db init and not change later on, so it is an unmanaged django model.
I can't find any good docs on this, how to create a django model dynamically or how to add fields to that model dynamically. I don't need it to be managed, no need of migrations or django admin view support. I only need it to work with django ORM and be able to join and filter on it.
I've read the docs and didn't find much. Most of the answers talk about why this is a bad idea but I don't see any other way of solving my problem (I have few other tables joined together to run a complex query and I need to do further filtration based on these properties and support pagination.

Django max_length where there should not be a max_length

I do not have a deep understanding of Django, anyway not deep enough to overcome a problem that turns up in my application.
In models.py I have a.o. the following definitions:
class Relatiedata(models.Model):
...
getuigen = models.TextField(blank=True, null=True)
...
class Meta:
db_table = 'relatiedata'
Relatiedata.objects = Relatiedata.objects.using('genealogie')
So in the database genealogie, which is not the default database, I have a table relatiedata with a column getuigen that has to contain a text string without a limitation on the length.
Further, I have a user form for mutating records of this table. As usual, the form is populated from a Relatiedata.object and the returned form results in another Relatiedata.object which is saved, thereby updating the database. This works (almost) perfect.
The problem is that in my form it turns out to be impossible to enter a string of length above 600 in the textarea for getuigen. Longer strings are simply cut off. There seems to be sort of a form validation for the length of that field, despite the fact that there is no such limit in the models, nor in the database, nor in the migration files.
This value of 600 comes from earlier, abandoned, implementations of the model, where originally I had a CharField with max_length 600 instead of a TextField.
All remarks are highly welcome.
EDIT
Some additional information. As it is now, the models were created from the already existing database, which is a simple sqlite database with some tables, no relations between the tables. The table relatiedata is a simple table with some textual columns, a little bit too large to show here. Makemigrations and migrate were of course used after the models were constructed, and at the moment makemigrations does not find anything to migrate.
Even worse: when I change the definition:
getuigen = models.CharField(max_length=2000, blank=True, null=True),
makemigrations shows this change and migrate solves it, but it is still impossible to use a string of more than 600 characters in the form. With less, it is OK.
Finally, I can change the value of the field getuigen to strings with more than 600 characters by using SQL. Having done that, in my application the long string turns up correctly in all output where it should be, even in my mutation form. But in the mutation form it cannot be edited because it is too long.
Make migrations and migrate again
python manage.py makemigrations specify_app_name
then
python manage.py migrate specify_app_name

Django default value in model based on data that hasn't been loaded yet

When creating migrations for Django I'm running into an instance where I need to set the default value for a custom user based on another table.
# models.py
def get_default_item():
return Item.objects.filter(name='XXXX').first().id
class CustomUser(AbstractUser):
# ...
item = models.ForeignKey(Item, on_delete=models.CASCADE, default=get_default_item)
# ...
I'm running into two issues:
I need to ensure that the table for Item is already created. I think I can do this using dependencies.
I need to ensure that the Item "XXXX" is created before it is referenced. Unfortunately this can't happen until I migrate the data over because the Item IDs need to be consistent with the old system and (unfortunately) I can't use id 0 with a Django / MySQL combination because that has special meaning.
Is there a way to tell the migration "don't worry about this default for now, you'll get it later"?

Is it safe to make a empty field non-empty for a existing database?

Hi, I'm trying to alter my current django project schema, the data migration tool is south. django version is 1.6.9.
It is a existing database so I don't want to mess up with my historical data.
What I'm trying to alter is making a blank=true field non-empty(blank=false)
here is my model class:
class Post(DraftableModel, EditTrackingModel):
title = models.CharField(max_length=120,
verbose_name='headline')
description = models.CharField(max_length=260,
blank=True,
verbose_name='lead-in',
help_text="260 character limit")
/*rest of the code*/
I want change the description from models.CharField(blank=True) to models.CharField(blank=False), which is the default blank value
considering the existence of my database, some of my old Post model do have empty description.
After my migration and change of database schema, will my database be corrupted?
When you try to migrate, django will warn you about those empty fields. so you have few options.
You can add a default value in your model like default="Some Default Value" and django will chose that default value for all empty fields on migration.
You can just send the migrate request and on the terminal, django will ask you to add an one-off value to be added to all the empty fields.
Also you can edit the migrate files and add different values for those empty fields based on conditions you have in mind.
You can write a function to check for all the empty fields for exiting rows and add some data based on some conditions.
Also i highly recommend to make a backup first. Doesn't matter how small the changes are or how good you are in coding.

Django-postgress: multiple primary keys are not allowed

when I am useing django.db.backends.postgresql_psycopg2 and running manage.py syncdb, following error raised
django.db.utils.ProgrammingError: multiple primary keys for table "token_place" are not allowed
LINE 3: "signatureid" integer NOT NULL PRIMARY KEY REFERENCES "s...
model:
class TokenPlace(models.Model):
token = models.ForeignKey(Token, db_column='tokenid', primary_key=True)
signature = models.ForeignKey(Signature, db_column='signatureid', primary_key=True)
place = models.IntegerField(primary_key=True)
class Meta:
db_table = 'token_place'
my models work correctly with mysql but I must deploy it in postgres
how to fix this problem?
After reading your answer I finally get the question, you are looking for composite keys in Django. Unfortunately this is not supported by Django yet. If you need it there are a few options:
Try the Django Composite Key project: https://github.com/simone/django-compositekey
Use the patches and explanation given on this page to add the support to Django: https://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys
Use SQLAlchemy (http://www.sqlalchemy.org/) for querying as it does support this properly.
Use a single primary key column in Django and read/write from/to a writable view which communicates with the actual table in the background.