【问题标题】:How to get total pv created for all of User's Django如何获得为所有用户的 Django 创建的总 pv
【发布时间】:2020-05-15 00:01:27
【问题描述】:

我有一个简单的模型:

class Pv(models.Model):
accounts =(
    ('Sub CF','Sub CF'),
    ('Special','Special'),
    ('Directors','Directors'),
    ('Operations','Operations'),
    ('LSGDP','LSGDP'),
    ('DWAP','DWAP'),
    ('Capacity(USD)','Capacity(USD)')
    )
acc =(
('Yes','Yes'),
('No', 'No')
)

source =(
        ('GOG','GOG'),
        ('Others', 'Others')
      )
pv =(
    ('General','General'),
    ('Honorarium','Honorarium')
   )
center=(
    ('Cost Center 1','Cost Center 1'),
    ('Cost Center 2','Cost Center 2'),
    ('Cost Center 3','Cost Center 3'),
    ('Cost Center 4','Cost Center 4'),
    ('Cost Center 5','Cost Center 5')
       )
stat =(
    ('Completed','Completed'),
    ('Returned','Returned'),
    ('Cancelled','Cancelled')
)
IA_System_Code = models.AutoField(primary_key = True)
IA_code = models.CharField(max_length = 150)
Date_recieved = models.DateField()
Pv_reference = models.CharField(unique = True, max_length = 120)
Source_of_Funding = models.CharField(max_length=50, choices = source)
Cost_center = models.CharField(max_length=50, choices = center)
Payee = models.CharField(max_length=500)
Description = models.CharField(max_length = 500)
Account_code = models.CharField(max_length=350)
Gross_amount = models.DecimalField(max_digits=19, decimal_places=2)
Withholding_tax = models.DecimalField(max_digits=19, decimal_places=2)
Net_amount = models.DecimalField(max_digits=19, decimal_places=2)
Status = models.CharField(max_length = 60, choices = stat )
Remarks =models.CharField(max_length = 500, blank = True)
Acc_Impress = models.CharField(max_length = 350,choices=acc)
Date_returned =models.DateField(null=True,blank = True)
Type_of_accounts= models.CharField(max_length = 100, choices = accounts)
Type_of_pv = models.CharField(max_length = 20, choices = pv)
returned_to_chest = models.DecimalField(max_digits=19, decimal_places=2)
created = models.DateTimeField(null=True)
created_by = models.ForeignKey('auth.User', blank=True, null=True,\ 
                               default=None,on_delete=models.CASCADE,related_name='create')
modified = models.DateTimeField(null=True)
modified_by = models.ForeignKey('auth.User', blank=True, null=True,\
                                 default=None ,on_delete=models.CASCADE,related_name='modified')
class Meta():
        ordering = ["IA_System_Code"]



def __str__(self):
    return self.Description

def save(self, *args, **kwargs):
    user = get_current_user()
    if user and not user.pk:
        user = None
    if not self.pk:
        self.created_by = user
        self.created = datetime.now()
    else:
        self.modified_by = user
        self.modified = datetime.now()
    super(Pv, self).save(*args, **kwargs) 

我正在努力弄清楚,我认为应该是一个简单的查询,使用 Django 的 ORM。

假设我总共有 3 个唯一用户创建的 6 个 PV 现在,我真正想要的是查询所有 pv 并计算每个用户创建的 pv,但只想要每个唯一用户中的一个并添加一个(什么我认为应该是一个带注释的)属性,称为每个用户的总数。我也不想在系统中显示没有进行任何 pv 条目的用户。

所以如果用户创建了 2 个 PV,他的总数将是 2。请任何人帮助我。 我如何将它作为表格显示在我的模板上。 示例:

   user   total pv recorded for the yr
   John       10
   peter      20
   pack        5

请任何人都可以帮助我。看起来我不知道在做什么。谢谢你

【问题讨论】:

    标签: django django-models django-templates django-views


    【解决方案1】:

    您可以编写此查询。 views.py

     from django.db.models import Count, Q # import Q here
     import datetime
     today = datetime.datetime.now()
     qry = User.objects.filter(Q(create__isnull=False) & Q(create__created__year=today.year)).\
           annotate(counter=Count('create')).\
           prefetch_related('create') # this will only count the PV s from current yaer
    

    在模板中发送qry

    模板

    {% for i in qry %}
    {% if i.counter != 0 %} # checking if PV exist for user
    # edited line
    <p>{{ i.first_name }} {{ i.counter }}</p> # first name number of PVs
    
    {% endif %}
    {% endfor %}
    

    我希望这会有所帮助。

    编辑

    您可以打印任何您想要的东西。 {{ j.description }} 例如。我已经编辑了代码。当前代码将打印 fisrt_name 和 counte (john 5)。您可以将 first_name 替换为任何类似的 first_name last_name count,或者您在模型中定义了 name已编辑 我编辑了你的查询,所以现在只计算那些只注册了 pv 的用户。现在我需要在新年开始时将计数器重置为零

    【讨论】:

    • 您的代码可以工作,但需要有用户,然后是总数。例如约翰 10
    • 我也不需要显示描述。
    • 您的代码可以工作,但需要有用户的全名,然后是总数。例如约翰 10
    • {{ j.Description }} 是例如。你可以在那里打印任何你想要的东西。 @TERKPEHMENSAH
    • 代码现在可以完美运行,除了它还带出了还没有注册任何 pv 的用户,如果我们进入新的一年,有没有办法让 i.counter =0 。示例 john 在 2020 年有 20 个,但如果我们进入 2021 年,john 的计数应反转为 0 并重新开始计数。谢谢你
    【解决方案2】:

    @sandeep 你的查询没有在模板上显示任何内容,所以我首先查询了所有用户

    查看.py

     from django.db.models import Count, Q 
     import datetime
      qry = User.objects.all()
    

    然后我用您的代码过滤了查询

    qryr = qry.filter(Q(create__isnull=False)\ &
                           Q(create__created__year=today.year))\
                           .annotate(counter=Count('create'))\
                           .prefetch_related('create').order_by('-counter')
    

    这是我的模板

    模板.html

    <table class="table table-bordered table-hover">
                 <thead>
                   <tr>
                     <th scope="col">Users</th>
                     <th scope="col">Pv's Recorded</th>
    
    
                   </tr>
                 </thead>
                 <tbody>
                    {% for i in qryr %}
                     
                   <tr>
                       <td>{{i.first_name}} {{i.last_name}}</td>
                       <td> {{ i.counter }}</td>
                   </tr>
                   {% endfor %}
                 </tbody>
               </table>
    

    非常感谢

    【讨论】:

    • 您可以删除此条件“{% if i.counter.count != 0 %}”。您已在此处过滤了 veiws 中的查询 (create__isnull=False)。它会起作用的
    • 如果您使用的是 filter(),则不必使用 all()。我一定错过了什么。但这会起作用。
    猜你喜欢
    • 2021-05-29
    • 1970-01-01
    • 2019-02-27
    • 2015-11-19
    • 2019-03-31
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多