7

Can I have in Django's model a column of PostgreSQL's "text" type? If so, how can I do that?

2 Answers 2

9

You can use the TextField

A large text field. The default form widget for this field is a Textarea.

Usage:

class MyModel(models.Model):
    text_field = models.TextField("My field label", null=True, blank=True)

If the text is not too long, You could also consider CharField

A string field, for small- to large-sized strings. For large amounts of text, use TextField.

The default form widget for this field is a TextInput.

Usage:

class MyModel(models.Model):
    text_field = models.CharField("My field label", max_length=1024, null=True, blank=True)
Sign up to request clarification or add additional context in comments.

Comments

1

A customized CharField will give "text" DB type benefits while remaining compatible with other site code.

class CharField(models.CharField):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('max_length', 65000)
        super(CharField, self).__init__(*args, **kwargs)

    def db_type(self, connection):
        return 'text'

    def south_field_triple(self):
        """Only necessary if using South migrations, which you should."""
        from south.modelsinspector import introspector
        field_class = self.__class__.__module__ + "." + self.__class__.__name__
        args, kwargs = introspector(self)
        return (field_class, args, kwargs)

Using this field instead of models.CharField() allows you to skip that pesky max_length and varchar updates.

class Sausage(models.Model):
    length = models.PositiveIntegerField()
    title = CharField()
    recipe = models.TextField()

Which gives following SQL:

CREATE TABLE "w00t_sausage" (
    "id" integer NOT NULL PRIMARY KEY,
    "length" integer unsigned NOT NULL,
    "title" text NOT NULL,
    "recipe" text NOT NULL
)

They are both 'text' in a database, but represented as usual in admin and form widgets.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.