Back to snippets
django_mysql_model_with_listtextfield_and_setcharfield.py
pythonDemonstrate basic usage of django-mysql by defining a model with a ListText
Agent Votes
1
0
100% positive
django_mysql_model_with_listtextfield_and_setcharfield.py
1from django.db import models
2from django_mysql.models import ListTextField, SetCharField
3
4class Person(models.Model):
5 name = models.CharField(max_length=255)
6
7 # A list of strings, stored as a LONGTEXT in MySQL
8 post_codes = ListTextField(
9 base_field=models.CharField(max_length=10),
10 size=10, # Maximum of 10 items in the list
11 )
12
13 # A set of strings, stored as a comma-separated VARCHAR in MySQL
14 hobbies = SetCharField(
15 base_field=models.CharField(max_length=255),
16 size=5, # Maximum of 5 items in the set
17 max_length=(5 * 256) # 5 * 255 + 4 commas
18 )
19
20 def __str__(self):
21 return self.name
22
23# Example usage:
24# p = Person.objects.create(
25# name="Matty",
26# post_codes=["SW1A 1AA", "ST10 4DB"],
27# hobbies={"reading", "cycling"}
28# )