Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create list field in django

How do I create a ListField in Django (Python) like the ListProperty property in Google App Engine (Python)? My data is a list like this : 3,4,5,6,7,8.

What property do I have to define and how would I fetch values from it?

like image 957
Madhur Avatar asked Mar 07 '11 05:03

Madhur


People also ask

What is field list in Django?

Fields in Django are the data types to store a particular type of data. For example, to store an integer, IntegerField would be used. These fields have in-built validation for a particular data type, that is you can not store “abc” in an IntegerField. Similarly, for other fields.

Is there ListField in Django?

If you are using Google App Engine or MongoDB as your backend, and you are using the djangoappengine library, there is a built in ListField that does exactly what you want. Further, it's easy to query the Listfield to find all objects that contain an element in the list.

How many fields are there in Django model?

Django Model Fields Django version 2.2 offers 26 different field types to capture different data formats.

What are model data types and fields in Django?

Django model data types and fields list. The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean, save, or delete.

What is Listfield in serializers in Django?

ListField in serializers - Django REST Framework - GeeksforGeeks. ListField. ListField is basically a list field that validates the input against a list of objects. How to use ListField in Serializers ? Validation on ListField. Advanced concepts.

What is an instance of a field class in Django?

Each field in the model should be an instance of the appropriate Field class. Django uses field class types to determine a few things: The column type, which tells the database what kind of data to store (e.g. INTEGER, VARCHAR, TEXT).

How to add search_fields to Django admin 4?

Adding search_fields to Django Admin 4. Conclusion First, let's create a model that we'll work with it. Let's now register our model in admin.py. As you can see, our model has been registered, now let's add some products to our model. in this image, Django displayed just the field name that we have returned in the __str__ method.


2 Answers

Revisiting this with a ListField type you can use. But it makes a few of assumptions, such as the fact that you're not storing complex types in your list. For this reason I used ast.literal_eval() to enforce that only simple, built-in types can be stored as members in a ListField:

from django.db import models import ast  class ListField(models.TextField):     __metaclass__ = models.SubfieldBase     description = "Stores a python list"      def __init__(self, *args, **kwargs):         super(ListField, self).__init__(*args, **kwargs)      def to_python(self, value):         if not value:             value = []          if isinstance(value, list):             return value          return ast.literal_eval(value)      def get_prep_value(self, value):         if value is None:             return value          return unicode(value)      def value_to_string(self, obj):         value = self._get_val_from_obj(obj)         return self.get_db_prep_value(value)  class Dummy(models.Model):     mylist = ListField() 

Taking it for a spin:

>>> from foo.models import Dummy, ListField >>> d = Dummy() >>> d.mylist [] >>> d.mylist = [3,4,5,6,7,8] >>> d.mylist [3, 4, 5, 6, 7, 8] >>> f = ListField() >>> f.get_prep_value(d.numbers) u'[3, 4, 5, 6, 7, 8]' 

There you have it that a list is stored in the database as a unicode string, and when pulled back out it is run through ast.literal_eval().

Previously I suggested this solution from this blog post about Custom Fields in Django:

An alternative to the CommaSeparatedIntegerField, it allows you to store any separated values. You can also optionally specify a token parameter.

from django.db import models  class SeparatedValuesField(models.TextField):     __metaclass__ = models.SubfieldBase      def __init__(self, *args, **kwargs):         self.token = kwargs.pop('token', ',')         super(SeparatedValuesField, self).__init__(*args, **kwargs)      def to_python(self, value):         if not value: return         if isinstance(value, list):             return value         return value.split(self.token)      def get_db_prep_value(self, value):         if not value: return         assert(isinstance(value, list) or isinstance(value, tuple))         return self.token.join([unicode(s) for s in value])      def value_to_string(self, obj):         value = self._get_val_from_obj(obj)         return self.get_db_prep_value(value) 
like image 177
jathanism Avatar answered Sep 24 '22 06:09

jathanism


Try using a CommaSeparatedIntegerField which is documented here: http://docs.djangoproject.com/en/1.2/ref/models/fields/#commaseparatedintegerfield

like image 42
Isaac C. Avatar answered Sep 20 '22 06:09

Isaac C.