【问题标题】:how to cut a record?怎么删记录?
【发布时间】:2014-09-29 07:55:48
【问题描述】:

请帮助避免代码重复。

我需要调用 get_new_authors_entries() 的 get_count_authors_entries()

from django.db import models
from django.contrib.auth.models import User, UserManager


class UserProfile(User):            
    phone = models.CharField(
        max_length=50, 
        blank=False,
    )
    skype = models.CharField(
        max_length=50, 
        blank=False,
    )   

    @classmethod
    def get_new_authors_entries(self):
        return self.objects.filter(is_active=1, is_superuser=0).order_by('-date_joined')    

    @classmethod
    def get_count_authors_entries(self):
        return self.objects.filter(is_active=1, is_superuser=0).order_by('-date_joined').count()        

【问题讨论】:

    标签: python django python-3.x


    【解决方案1】:

    首先,不要将参数调用到类方法self。按照惯例,它用于实例:类方法的参数是cls

    其次,方法之间的唯一区别是添加了count()。那么为什么你不能把它放在调用另一个的结果上呢?

    @classmethod
    def get_count_authors_entries(cls):
        return cls.get_new_authors_entries().count()
    

    还要注意,在 Django 中,将这些方法放在自定义管理器上比使用类方法更惯用。最后,我会质疑你为什么需要 count 方法,因为你可以将 count() 添加到 get_new_authors_entries 方法的结果中,无论你在哪里调用它。

    【讨论】:

      【解决方案2】:

      如果您可以使用一种方法,则无需定义两种方法。

      @classmethod
      def get_authors_entries(cls):
          return self.objects.filter(is_active=1, is_superuser=0).order_by('-date_joined')
      

      现在,如果您想获取新的作者条目,只需调用 get_authors_entries,如果您想获取计数,只需在返回的查询集上调用 count 方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-23
        • 1970-01-01
        • 2019-01-22
        • 1970-01-01
        • 1970-01-01
        • 2013-07-01
        • 1970-01-01
        相关资源
        最近更新 更多