What's the difference between CharField and TextField in Django?
It's a difference between RDBMS's varchar
(or similar) — those are usually specified with a maximum length, and might be more efficient in terms of performance or storage — and text
(or similar) types — those are usually limited only by hardcoded implementation limits (not a DB schema).
PostgreSQL 9, specifically, states that "There is no performance difference among these three types", but AFAIK there are some differences in e.g. MySQL, so this is something to keep in mind.
A good rule of thumb is that you use CharField
when you need to limit the maximum length, TextField
otherwise.
This is not really Django-specific, also.
What is the difference between SlugField() vs CharField() in Django models
A slug is a string without special characters, in lowercase letters and with dashes instead of spaces, optimal to be used in URLs. An example of slug could be:
example/this-is-a-slug/150
you can look for more information here Documentation django slug
CharField has max_length of 255 characters , and accept special characters.
About CharField Here
Django: Difference between blank=True and default=
Blank and Default arguments are not interchangeable. The resulting interaction will be different, depending on what combination you use. For example,
some_field = models.CharField(default='', max_length=20)
...will not allow you to save the model instance without entering data into some_field. The default empty string in this case is just allowing you to add that field to the model upon migration, since you aren't also allowing null with null=True.
some_field = models.CharField(blank=True, default='', max_length=20)
...will save without data, since blank=True.
Another way of putting this is that your default='' is allowing the non-nullable field to exist, and blank=True is allowing your non-nullable field to save() without data entry. If you try to migrate the following:
some_field = models.CharField(max_length=20)
...you'll get the following error:
You are trying to add a non-nullable field 'some_string' to YourModelName without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
...since a non-nullable field without a default can't exist on the database, but a blank=True field can. Note, I'm speaking here of PostgeSQL. This may or may not apply to any/every other DB out there.
What is the max size of 'max_length' in Django?
That depends on the database backend. The Django DB Docs will tell you, that max_length=255
is guaranteed to work always.
If you need something of the amount you've specified in your question, I'd suggest to use a TextField.
How do I query for greater than on a textfield in Django?
There is a Cast function that you can use in conjunction with annotating. Hopefully the below will do the trick:
from django.db.models.functions import Cast
from django.db.models import IntegerField
MyTable.objects.annotate(text_int=Cast('text_field', output_field=IntegerField())).filter(text_int__gte=100)
What is the difference between timezone.now and db.models.functions.Now?
The timezone.now(…)
function [Django-doc] returns a datetime
object with the timezone, given the USE_TZ
setting [Django-doc] is used.
Now
[Django-doc] on the other hand, is a database expression. Indeed, it does not determine a datetime
. It will use NOW()
at the database side where you query. It will thus work with the clock of the database. If the database thus runs on the same server, it is the server time, whereas if it runs on a different server, it can be a few seconds/minutes earlier/later if the clocks of the two systems are not completely in sync.
If you thus query with:
from django.utils import timezone
Post.objects.filter(published_at__lte=timezone.now())
Then it will make a query that looks like:
SELECT post.*
FROM post
WHERE published_at <= 2022-07-27 15:40:00 -- time from Django/Python
whereas if we use:
from django.db.models.functions import Now
Post.objects.filter(published_at__lte=Now())
it will query with:
SELECT post.*
FROM post
WHERE published_at <= NOW() -- databae timestamp
Django TextField and CharField is stripping spaces and blank lines
If you are looking for a text/char field and do not want it to strip white spaces you can set strip=False in the constructor method of a form and then use the form in the admin
class YourForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(YourForm, self).__init__(*args, **kwargs)
self.fields['myfield'].strip = False
class Meta:
model = YourModel
fields = "__all__"
You can then use this form in the admin by specifying form=YourForm
in the admin.py file.
Related Topics
Should Every SQL Server Foreign Key Have a Matching Index
Sql: Using Null Values VS. Default Values
How to Retrieve Field Names from Temporary Table (SQL Server 2008)
Inserting into Oracle and Retrieving the Generated Sequence Id
How to Find Sum of Multiple Columns in a Table in SQL Server 2005
SQL Server Join Tables and Pivot
Using Bind Variables with Dynamic Select into Clause in Pl/Sql
How to Get the Full Resultset from Ssms
Select First Record in a One-To-Many Relation Using Left Join
Get the First and Last Date of Next Month in MySQL
How to Execute a Native SQL Script in JPA/Hibernate
SQL Query for Getting Data for Last 3 Months
Timestamp Difference in Hours for Postgresql
In Oracle, How to Insert or Update a Record Through a View
Query Times Out from Web App But Runs Fine from Management Studio
Why Doesn't Oracle SQL Allow Us to Use Column Aliases in Group by Clauses