gpt4 book ai didi

python - Django:如何计算数据库中与另一个对象相关的对象数量?

转载 作者:太空宇宙 更新时间:2023-11-03 19:29:58 29 4
gpt4 key购买 nike

我想要制作一个应用程序,允许人们组成团体一起购买元素。我需要一种方法来查看有多少人已经在购买。我有以下 models.py:

from django.db import models

class Buyer(models.Model):
''' Buyer of the item '''

first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=40)
email = models.EmailField()

# Pieces together full name from first and last
def full_name(self):
return "%s %s" % self.first_name, self.last_name

# String representation of buyer in the format 'firstname lastname (email)'
def __unicode__(self):
return "%s (%s)" % self.full_name, self.email

class Item(models.Model):
'''The item being purchased'''

name = models.CharField(max_length=50)
description = models.TextField()
price = models.DecimalField(max_digits=6, decimal_places=2)
# The number of items to be split
quantity = models.IntegerField()
pub_date = models.DateTimeField('Date Offered')
# Expiration of the item on offer
expires = models.DateField()

# Relates item to buyers
buyers = models.ManyToManyField(Buyer)

# Calculates remaining slots
def remaining(self):
# How do I do this?

# String representation of item using item name
def __unicode__(self):
return self.name

我从概念上知道,我只需要获取报价中的数量并减去买家的数量,但我真的不知道如何实现这一点。根据我所读到的内容,我似乎可以用这样的方法来做到这一点:

def remaining(self):
return self.objects.aggregate(Count('buyers'))

不过我不是很有信心。谁能帮助我找到最好的方法?

最佳答案

您可以直接获取结果,然后对它们进行计数:

def remaining(self):
return self.quantity - len( self.buyers.all() )

实际上,要更新,documentation说不要这样做,尽管它会起作用,所以:

def remaining(self):
return self.quantity - self.buyers.all().count()

关于python - Django:如何计算数据库中与另一个对象相关的对象数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6365210/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com