routeburn
routeburn

Reputation: 1166

Storing lists of words in database - best practice

I'm implementing a user filter system on a website. Users are to be able to select 'categories' and 'packages' of interest to them and have the matching data presented when they log in. Both sets of data will come from HTML select forms eg. Categories: 'null pointers', 'dead code'... and packages 'package_x', 'package_y', 'package_z'...

My question is about the best way to store this list information in a database (I am using Django and PostgresSQL).

My initial thought is to have a table like this:

user_id - one to one field
categories - textfield - store json data
packages - textfield - store json data

Is there a better way to be doing this?

Upvotes: 0

Views: 306

Answers (1)

Nathaniel
Nathaniel

Reputation: 696

I would go the route of using a user profile with categories and packages being many to many fields.

In models.py

from django.contrib.auth.models import User

class Category(models.Model):
    name = models.CharField(max_length=255)

class Package(models.Model):
    name = models.CharField(max_length=255)

class UserProfile(models.Model):
    user = models.ForiegnKey(User)

    categories = models.ManyToManyField(Category)
    packages = models.ManyToManyField(Package)

In admin.py

from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class CustomUserAdmin(UserAdmin):     
    inlines = [UserProfile]
    #filter_horizontal = ('',) #Makes the selection a bit more friendly

admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

In views.py

user_with_profile = User.objects.get(pk=user_id).get_profile()

All that being said. Django 1.5 will replace the user profile with being able to use a configurable user model.

Upvotes: 1

Related Questions