0

I have a departmental structure, where reports belong to a subset of Departments. In this case, a Department can be a county, and a report has an FK to a county.

class Report(models.Model):
    user = models.ForeignKey(User)
    value = models.IntegerField()
    county = models.ForeignKey('Department')


class CountyDepartmentManager(models.Manager):
    def get_queryset(self):
        return super(CountyDepartmentManager, self).get_queryset().filter(county=True)


class Department(models.Model):
    name = models.CharField(max_length=256)
    county = models.BooleanField(default=0)

    objects = models.Manager()
    county_objects = CountyDepartmentManager()

I would like Report.county to use CountyDepartmentManager() so only counties appear in the Report.county select field.

Is it even possible, or do I have to make these definitions in the Form class?

Rob L
  • 3,634
  • 2
  • 19
  • 38
  • it is possible, did you try it? – doniyor Jan 29 '16 at 15:56
  • Well, I don't know how to implement it. What parameters or settings do I need to add to the `county` field to make it use the `CountyDepartmentManager`? – Rob L Jan 29 '16 at 16:28
  • you can see here, it is actually easy to follow: https://docs.djangoproject.com/en/1.9/topics/db/managers/#modifying-initial-manager-querysets – doniyor Jan 29 '16 at 16:33
  • I don't see anything in that documentation that tells me how to set the FK to use a manager other than the default, i.e., `county = models.ForeignKey('Department')` will get all the `Department` objects, rather than the subset returned by `CountyDepartmentManager`. – Rob L Jan 29 '16 at 16:58

1 Answers1

0

Well, I suspect it isn't possible. Further, I guess that the reason is that creating a new instance with the limited manager would require some ugly plumbing.

In any case, I solved it by creating an umnanaged County model.

class County(models.Model):

    name = models.CharField(max_length=256)
    is_county = models.BooleanField(default=0)

    objects = CountyDepartmentManager()

    class Meta:
        managed = False
        db_table = 'department'

I originally was going to extend Department, but that ended up making the County.objects.all() query error out. It was looking for department.department_ptr_id

If anyone has some more info about this, I would love to hear it.


EDIT: I was able to do it by making County a proxy model that extends Department.

class County(Department):
    objects = CountyDepartmentManager()

    class Meta:
        proxy = True
Rob L
  • 3,634
  • 2
  • 19
  • 38