Django FK using Custom Manager

54 views Asked by At

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?

1

There are 1 answers

0
Rob L On

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