1

I have a model in Django with a method that I can't seem to access in the view. Here is the model:

class Realtor(models.Model):
    user = models.OneToOneField(User)
    team = models.ForeignKey(RealtorTeam, blank=True, null=True, default=None)
    is_showing_realtor = models.BooleanField(default=False)
    is_listing_realtor = models.BooleanField(default=False)

    def type(self):
        if self.is_showing_realtor and self.is_listing_realtor:
            return 'Showing and Listing'
        elif self.is_showing_realtor:
            return 'Showing'
        elif self.is_listing_realtor:
            return 'Listing'
        else:
            return ''

Now, in the view, I try to query the model, including the method, like this:

q = Realtor.objects.all()
q = q.filter(user__first_name__icontains=first)
q = q.filter(user__last_name__icontains=last)
q = q.filter(team__name__icontains=team)
q = q.filter(user__email__icontains=email)
q = q.filter(type__icontains=type)

The error I get is Cannot resolve keyword 'type' into field. Choices are.... I looked up a number of stackoverflow questions, and read through more of the Django docs, and I saw to add a field like this in the model:

type_display = (type,)

But that didn't work. Do I have to query the is_showing_realtor and is_listing_realtor? Is there no way to query the method?

More info

We are using Django_tables2 to display tables of models. We are able to access the type method with that, like this:

class RealtorTable(tables.Table):
    id = tables.Column()
    first_name = tables.Column(accessor='user.first_name', order_by='user.first_name')
    last_name = tables.Column(accessor='user.last_name', order_by='user.last_name')
    team = tables.Column()
    email = tables.Column(accessor='user.email', order_by='user.email')
    type = tables.Column(order_by='is_showing_realtor')

But still, can't pass it to the view.

4

2 回答 2

2

type是一个内置函数python 的名称,在 django 中也是如此。我建议将您的函数重命名listing_type为避免任何冲突。

特别是,这条线

type_display = (type,)

可能没有做你认为的那样。

reptilicus是正确的,我没有在非字段属性上发现过滤器,这没有意义。您可以listing_type变成一个CharFieldwith choices=set,然后save()在模型更改时使用一些自定义逻辑来设置它 - 或者您可以使用property

@def listing_type():
    doc = "The listing_type property."
    def fget(self):
        if self.is_showing_realtor and self.is_listing_realtor:
            return 'Showing and Listing'
        elif self.is_showing_realtor:
            return 'Showing'
        elif self.is_listing_realtor:
            return 'Listing'
        else:
            return ''
    def fset(self, value):
        self._listing_type = value
    def fdel(self):
        del self._listing_type
    return locals()
listing_type = property(**listing_type())

PS我还是不喜欢type:-)

于 2013-02-05T18:01:16.840 回答
1

我不是 Django 专家,但我很确定您无法查询不是数据库中列的模型属性,而这正是您想要做的。也许尝试用它来装饰方法,@property使其像一个属性。

如果喜欢,你可以做一个列表理解

results = [m for m in query_set if m.type = "Showing and listing"]
于 2013-02-05T18:18:38.517 回答