Error while changing a Char field to Array Field in Django - python

I am trying to change a existing CharField in a django model (it also allows null and contains null values in db currently)
now I am trying to change it to an Array Char Field, but it throws the below error
"django.db.utils.IntegrityError: column "tags" contains null values"
From
tags= models.CharField(max_length=255, blank=True, null=True)
To
tags = ArrayField(models.CharField(max_length=255, blank=True, null=True))
I have selected option 2 while before running migrate

In this option 2 you selected, you were asked to select a default value yourself, right?
Add a default attribute to your model's field. The existing null values will be turned into that value, for instance:
tags = ArrayField(models.CharField(max_length=255, blank=True, null=True, default=[]))

Related

Django CharField with dynamic default value

I want to add a new field to a PostgreSQL database.
It's a not null and unique CharField, like
dyn = models.CharField(max_length=31, null=False, unique=True)
The database already has relevant records, so it's not an option to
delete the database
reset the migrations
wipe the data
set a default static value.
How to proceed?
Edit
Tried to add a default=uuid.uuid4
dyn = models.CharField(max_length=31, null=False, unique=True, default=uuid.uuid4)
but then I get
Ensure this value has at most 31 characters (it has 36).
Edit 2
If I create a function with .hex (as found here)
def hex_uuid():
"""
The UUID as a 32-character lowercase hexadecimal string
"""
return uuid.uuid4().hex
and use it in the default
dyn = models.CharField(max_length=31, null=False, unique=True, default=hex_uuid)
I'll get
Ensure this value has at most 31 characters (it has 32).
Note: I don't want to simply get a substring of the result, like adjusting the hex_uuid() to have return str(uuid.uuid4())[:30], since that'll increase the collision chances.
I ended up using one of the methods shown by Oleg
def dynamic_default_value():
"""
This function will be called when a default value is needed.
It'll return a 31 length string with a-z, 0-9.
"""
alphabet = string.ascii_lowercase + string.digits
return ''.join(random.choices(alphabet, k=31)) # 31 is the length of the string
with
dyn = models.CharField(max_length=31, null=False, unique=True, default=dynamic_default_value)
If the field was max_length of 32 characters then I'd have used the hex_uuid() present in the question.
If I wanted to make the dynamic field the same as the id of another existing unique field in the same model, then I'd go through the following steps.
you can reset the migrations or edit it or create new one like:
python manage.py makemigrations name_you_want
after that:
python manage.py migrate same_name
edit:
example for funcation:
def generate_default_data():
return datetime.now()
class MyModel(models.Model):
field = models.DateTimeField(default=generate_default_data)

Django - Many to Many Field Ordering Issue

class Sandeep(models.Model):
model_id = models.CharField(max_length=200, unique=True)
processors2 = models.ManyToManyField(ConfiguratorProduct,blank=True,
related_name="processors2", verbose_name="Processors2")
model_sk= models.CharField(max_length=200, unique=True)
model_dk = models.CharField(max_length=200, unique=True)
model_pk = models.CharField(max_length=200, unique=True)
models.DateTimeField(auto_now_add=True).contribute_to_class(
Sandeep.processors2.through, 'date_added2')
The above is my model and I am using processors2 as a Many to many Field. I want to save many to many field in the same order which i am adding to Sandeep from django Admin but my order get shuffled by the default id of ConfiguratorProduct[Manyto many relation model]
I tried using the above statement and successfully added one new field timestamp but not able to get the data into django admin UI as per the time-stamp.
I have checked so many solutions but not able to find out the best way to display many to many field in the same order which I am adding to the Model.

Django many-to-many query matching all related fields

I have two models connected by a many-to-many relationship in django.
class BuildingMapping(models.Model):
name = models.CharField(max_length=1000, null=False)
buildings = models.ManyToManyField(
Building, related_name="mapping"
)
class Building(models.Model):
function = models.CharField(
max_length=1000, blank=True, null=True
)
Function is a string containing one or more identifier divieded by a "/" e. g. "1300", "1300/2200", "1300/2230/7500", ...
I now want to perform a query that gets only BuildingMapping instances where the function for all Buildings is identical. I tried the following, but this will also return BuildingMapping instances where only one Building has "1300" as function.
BuildingMapping.objects.filter(buildings__function="1300")
Thanks!
If I understood correct, you want to get function field contains "1300". If it is right:
BuildingMapping.objects.filter(buildings__function__contains="1300")
I see that you are trying to fetch all the results which are matching 1300. What you are doing is exact match
strong text
You need to use icontains(case insensitive) or contains(case sensitive) for getting all matched data

Django ModelForm won't allow Null value for required field?

I have a Model with this field...
fulfillment_flag = models.CharField(pgettext_lazy('Delivery group field', 'Fulfillment Flag'), max_length=255,
null=True, choices=FULFILLMENT_FLAG_CHOICES)
And here is my form...
class FulfillmentFlagForm(forms.ModelForm):
class Meta:
model = DeliveryGroup
fields = ['fulfillment_flag', ]
def clean_fulfillment_flag(self):
return self.cleaned_data['fulfillment_flag'] or None
I have an HTML select drop down that has a blank value option at the top. Every time I select the blank option and click Save, form will not save it as a Null value on my model. It'll save any of the other fields though, just not the blank one. And it will tell me that the field is required as well.
How can I tell the form to just save the blank value as Null?
https://docs.djangoproject.com/en/1.8/ref/models/fields/#null
Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL.
For both string-based and non-string-based fields, you will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank).
Do blank=True instead and save "" instead of None.

Can I change the type of Model Field?

Say, I have a model with this field:
is_retired = models.NullBooleanField()
It has never been set for any of the records i the database, so I think all the records will have a null value for this field.
And now want to change it to a string field:
is_retired = models.CharField(max_length=50)
I am using Django 1.7 and ran makemigrations which seemed to go fine, said something about altered field. However, when I actually run the migrate command it fails with
django.db.utils.IntegrityError: column "is_retired" contains null values
How can I resolve this?
If you want to enable null/empty values, change it to:
is_retired = models.CharField(max_length=50, null=True, blank=True)
You might also want to change the null values to empty strings ('') in another migration.

Categories

Resources