开发者

Django ManyToMany field not preselecting rows with custom manager

开发者 https://www.devze.com 2023-03-14 20:43 出处:网络
Django 1.2.5: I\'ve got a model with a custom manager. Data is saved correctly, but it\'s not retrieved correctly for related objects.

Django 1.2.5: I've got a model with a custom manager. Data is saved correctly, but it's not retrieved correctly for related objects.

My models are:

  • Question -> related to a SubjectiveStatistic
  • SubjectiveStatistic extends Statistic as a Proxy. It has a custom manager to restrict the result set to only where the 'type' field matches 'SubjectiveStatistic' (the type field contains the class name of the object).

Here's the Question:

class Question(models.Model):
    subjective开发者_如何转开发_statistic = models.ManyToManyField(SubjectiveStatistic, null=True, blank=True)

Here is the SubjectiveStatistic:

class SubjectiveStatistic(Statistic):
    ## Use a custom model manager so that the default object collection is
    # filtered by the object class name.
    objects = RestrictByTypeManager('SubjectiveStatistic')

    ## Override the __init__ method to set the type field
    def __init__(self, *args, **kwargs):
        self.type = self.__class__.__name__
        return super(SubjectiveStatistic, self).__init__(*args, **kwargs)

    class Meta:
        proxy = True

Here is the manager:

from django.db import models

## Custom model manager that returns objects filtered so that 'type' == a
# given string.
class RestrictByTypeManager(models.Manager):
    def __init__(self, type='', *args, **kwargs):
        self.type = type
        return super(RestrictByTypeManager, self).__init__(*args, **kwargs)

    def get_query_set(self):
        return super(RestrictByTypeManager, self).get_query_set().filter(type=self.type)

What do I need to do so that related objects are returned correctly? question.subjective_statistic.exists() doesn't return anything, despite relations existing in the database.

Perhaps it's because the RestrictByTypeManager extends Manager instead of ManyRelatedManager (but I can't because that's an inner class) or something like that?


To use your custom manager from the Question model, add use_for_related_fields = True in the definition of the custom manager:

from django.db import models

## Custom model manager that returns objects filtered so that 'type' == a
# given string.
class RestrictByTypeManager(models.Manager):

    use_for_related_fields = True

    def __init__(self, type='', *args, **kwargs):
        self.type = type
        return super(RestrictByTypeManager, self).__init__(*args, **kwargs)

    def get_query_set(self):
        return super(RestrictByTypeManager, self).get_query_set().filter(type=self.type)

This way, RestrictByTypeManager will be used as manager for SubjectiveStatistic models either directly or in reverse access like with manytomany relations.

More informations here: Controlling automatic Manager types

0

精彩评论

暂无评论...
验证码 换一张
取 消