2013-10-15 68 views
0

寻找建立此模型的建议。Django模型 - 建立“has_many_through”关系

这个工作板应用程序有公司,位置和工作。他们应该有以下关系:

  • ,公司可以有多个位置
  • ,公司可以有多个作业
  • 一个作业只能有一个公司
  • 作业可以具有多个位置,但每地点必须是有效的工作的公司

我想创建一个模型,反映这些关系。我觉得这样的事情可能工作:

class Company(models.Model): 
    name = models.CharField(max_length=200) 
    description = models.TextField() 

class Location(models.Model): 
    is_primary_location = models.BooleanField() 
    address = models.CharField(max_length=200) 
    company = models.ForeignKey(Company) 

class Job(models.Model): 
    title = models.CharField(max_length=200) 
    company = models.ForeignKey(Company) 
    location = models.ForeignKey(Location) 

但我真的很喜欢“招聘具有位置(一个或多个)通过公司”关系被强制执行。该模型没有强制执行;我想我必须在数据显示时过滤有效的位置,我想避免这种情况。

非常感谢!

回答

0

看看ForeignKey.limit_choices_to

这允许您过滤可用选项,并在ModelForm中执行。由于您已在Job模型中拥有公司外键,因此您应该可以使用它来过滤选择。

0

我结束了使用https://github.com/digi604/django-smart-selects并写了这样的模型。我不认为limit_choices_to在这种情况下工作(根据其他SO线程)

from smart_selects.db_fields import ChainedForeignKey 

class Company(models.Model): 
    name = models.CharField(max_length=200) 
    description = models.TextField() 

class Location(models.Model): 
    is_primary_location = models.BooleanField() 
    address = models.CharField(max_length=200) 
    company = models.ForeignKey(Company) 

class Job(models.Model): 
    title = models.CharField(max_length=200) 
    company = models.ForeignKey(Company) 
    location = ChainedForeignKey(
     Location, 
     chained_field="company", 
     chained_model_field="company", 
     show_all=False, 
     auto_choose=True 
    ) 
+0

我结束了不使用智能选择,而是只是增加了一个验证规则时,作业保存:'如果(self.company_id! = Location.objects.get(pk = self.location_id).company_id): raise ValidationError('Location is not valid for company')' – billrichards