How would you inherit and replace the django template classes to create a listOfStringsField object?

advertisements

I want to create a new type of field for django models that is basically a ListOfStrings. So in your model code you would have the following:

models.py:

from django.db import models

class ListOfStringsField(???):
    ???

class myDjangoModelClass():
    myName = models.CharField(max_length=64)
    myFriends = ListOfStringsField() #

other.py:

myclass = myDjangoModelClass()
myclass.myName = "bob"
myclass.myFriends = ["me", "myself", "and I"]

myclass.save()

id = myclass.id

loadedmyclass = myDjangoModelClass.objects.filter(id__exact=id)

myFriendsList = loadedclass.myFriends
# myFriendsList is a list and should equal ["me", "myself", "and I"]

How would you go about writing this field type, with the following stipulations?

  • We don't want to do create a field which just crams all the strings together and separates them with a token in one field like this. It is a good solution in some cases, but we want to keep the string data normalized so tools other than django can query the data.
  • The field should automatically create any secondary tables needed to store the string data.
  • The secondary table should ideally have only one copy of each unique string. This is optional, but would be nice to have.

Looking in the Django code it looks like I would want to do something similar to what ForeignKey is doing, but the documentation is sparse.

This leads to the following questions:

  • Can this be done?
  • Has it been done (and if so where)?
  • Is there any documentation on Django about how to extend and override their model classes, specifically their relationship classes? I have not seen a lot of documentation on that aspect of their code, but there is this.

This is comes from this question.


What you have described sounds to me really similar to the tags.
So, why not using django tagging?
It works like a charm, you can install it independently from your application and its API is quite easy to use.