I am new to Django and I am trying to build a data hierarchy that follows this pattern:
There will be several Communities – say Huntsville, Phoenix, and Madison.
Each of those communities will be able to have several distinct Categories. For example, Huntsville may have Hunting, fishing, and skiing – and Phoenix may have running, biking, and swimming. Then each of the particular categories will have a number of distinct detail views. I tried to make this happen with:
from django.db import models
class Community(models.Model):
name = models.CharField(max_length=200) #arbitrary max length
class Category(models.Model):
community = models.ForeignKey(Community)
category = models.CharField(max_length=200) #arbitrary max length
class Detail_View(models.Model):
category = models.ForeignKey(Category)
detailView = models.CharField(max_length=200) #arbitrary max length
website = models.CharField(max_length=200) #arbitrary max length
but it doesn’t really seem to be working the correctly and I can’t quite figure out why.
Any thoughts?
I’m not sure I fully understand the behavior you’re looking for, but I have some advice anyway.
First, it looks like you’re implementing a one-to-many when you really want a many-to-many.
Check out http://docs.djangoproject.com/en/1.3/ref/models/relations/
Per that link, use
models.ManyToManyFieldinstead ofmodels.ForeignKeyAlso if you meant to define this as a one-to-many, you probably don’t want
Categoryto referenceCommunity. Use the phrase “has a” or “has many” to determine this. Since aCommunity“has a”Category, theForeignKey(orManyToManyField) should be defined on theCommunitymodel, not theCategoryone.I’d strongly recommend taking a look at the freely available Django Book project, especially the chapter on Advanced Models
Hope this helps!