Help with Django Model relationship & admin screen
My first time with Django and StackOverflow so could do with a little help.
A Platform has many Categories and a Category can belong to many Platforms. A product belongs to one Platform and one or more of that Platforms Categories.
So this is what I have so far for my Models:
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
is_active = models.BooleanField(default=True)
def __unicode__(self):
return self.name
class Platform(models.Model):
name = models.CharField(max_length=50, unique=True)
is_active = models.BooleanField(default=True)
categories = models.ManyToManyField(Category)
开发者_如何学编程 def __unicode__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=50)
is_active = models.BooleanField(default=True)
platform = models.ForeignKey('Platform')
def __unicode__(self):
return self.name
class Meta:
unique_together = ("platform", "category")
All looks ok when in shell but what I can't fully understand is how do I narrow down the Categories down based upon the Platform when I create a new Product? Ideally I would be able to get this working within the admin screens?
Does this Model look ok or can I do it better?
I have a feeling what you're asking is that, when using the admin interface and creating a new Product
model, you want to be able to select a Platform
, and then, be able to select a category, where by the category options given are only those already associated with the chosen Platform
.
That my friend is a bit more difficult than it would seem. The reason why is that built into django there is no server "round trip" whereby after Platform
has been selected the web app makes a trip to the server, gathers the options for Category
, then displays it to you. There isn't such an option by default (though I wouldn't be surprised if this eventually becomes included as part of the standard Django package).
However, there is a way to do this by implement it in javascript/ajax, which can be slightly challenging depending on your experience with either.
The good news is, as with most common tasks in Django, there's usually a community app either in development or already available to meet the need. In this case it'd probably be worth checking out django-ajax-filtered-field.
精彩评论