Django Model Field Default to Null - python

I need to have my Django application allow me to have a default value of NULL set for a certain model field. I've looked over the null, blank, and default parameters, but it's not very clear what combination of the three I need to use to get the desired effect. I've tried setting default=NULL but it threw an error. If I specify blank=True, null=True and no default, will it just default back to NULL come runtime?

Try default=None. There is no NULL in python.

If you specify null=True on the model field then the value will be stored as NULL in the database if the user does not provide a value.

blank=True
allows you to input nothing (i.e "", None) and keep it empty.
null=True
means the database row is allowed to be NULL.
default=None
sets the field to None if no other value is given.

Related

Django implementation of default value in database

I had a field on a model with was:
class SomeModel(models.Model):
some_field = models.CharField(max_length=10, null=True, blank=True)
Then I changed my model to:
class SomeModel(models.Model):
some_field = models.CharField(max_length=10, default='')
When I ran django-admin sqlmigrate somemodels somemigration to check my migration I found the following changes:
ALTER TABLE "somemodels" ALTER COLUMN "some_field" SET DEFAULT '';
UPDATE "somemodels" SET "some_field" = '' WHERE "some_field" IS NULL;
ALTER TABLE "somemodels" ALTER COLUMN "some_field" SET NOT NULL;
ALTER TABLE "somemodels" ALTER COLUMN "some_field" DROP DEFAULT;
I am not understanding why the Django apply a DROP DEFAULT in the table since I am creating a default value. If this is correct, how does Django implement the default values?
Information about my tools:
Postgresql 9.5;
Django 1.11b1;
The comments to django/db/backends/base/schema.py, starting ln. 571, detail the steps involved here:
When changing a column NULL constraint to NOT NULL with a given default value, we need to perform 4 steps:
Add a default for new incoming writes
Update existing NULL rows with new default
Replace NULL constraint with NOT NULL
Drop the default again.
Django does not usually use the built-in SQL default to set values (remember that Django can use callable values for defaults). You can find more information in this rejected bug report.

Django IntegrityError with DateTimeField

I have field in my model as follows.
view_time = ArrayField(
models.DateTimeField(auto_now_add=True))
but i get error:
django.db.utils.IntegrityError: null value in column "view_time"violates not-null constraint
DETAIL: Failing row contains (18, 0, null, null, null).
error arises when i try to create new object, and add value:
recent_views = UserRecentViews.objects.create()
recent_views.add_view(product.article)
i use django 1.8.8 and Python 3.5.2
i reset database fiew times but it doesn`t help, db is Postgres.
I think problem in object creation? but why django can not create object with current datetime? auto_now_add=True was added for this.
My question is how add autogenerated datetime field with django?
First of all, your database appears to be incompletely normalized. The use of comma separate values in a column or an array type is usually a good indication of that.
Secondly.
Tip: Arrays are not sets; searching for specific array elements can be
a sign of database misdesign. Consider using a separate table with a
row for each item that would be an array element. This will be easier
to search, and is likely to scale better for a large number of
elements.
Arrays are just postgresql's way of giving you enough rope to ...
Your best bet really is to normalize your database. Your inferior option is to set blank=True, null = True
view_time = ArrayField(
models.DateTimeField(auto_now_add=True), blank=True, null=True)
That's because when you do the following django has no reason to create any DateTimeField objects at all.
recent_views = UserRecentViews.objects.create()
So it just sets the array field as null, which is not allowed.
Oh to be more specific
but why django can not create object with current datetime
because you are not telling it to.

Django - filter model

I have a model with a field that is a list.
For example:
mymodel.sessions = [session1, session2]
I need a query to get all mymodels that session1 is exist their sessions.
The model`s field looks like that
sessions = models.ForeignKey("Session", related_name="abstracts",
null=True, blank=True)
Thank you !
You can use reverse lookups that go back along the foreign key to query for values in the related model.
MyModel.objects.filter(sessions__id=1)
That will filter all MyModels that have a foreign key to a session with an id of 1.
For more information see https://docs.djangoproject.com/en/1.10/topics/db/queries/#lookups-that-span-relationships
From the Django docs for filter:
filter(**kwargs)
Returns a new QuerySet containing objects that match the given lookup parameters.
You can filter on a ForeignKey relationship using the id, if you have it:
The field specified in a lookup has to be the name of a model field. There’s one exception though, in case of a ForeignKey you can specify the field name suffixed with _id. In this case, the value parameter is expected to contain the raw value of the foreign model’s primary key.
In your instance, this would like the following:
mymodel.objects.filter(sessions_id=4)
If you want to filter on any other field in the Sessions model, simply use a double underscore with the field. Some examples:
mymodel.objects.filter(sessions__name='session1')
mymodel.objects.filter(sessions__name__contains='1')

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