如何使用django的queryset从MyUser表中获取用户列表,其中UserBankTransaction表中的transaction_paid为False?
class UserBankTransaction(models.Model):
user = models.ForeignKey(MyUser)
plaid_transaction_id = models.CharField(max_length=300, unique=True)
charge_amount = models.DecimalField(max_digits=10, decimal_places=2)
account_id = models.CharField(max_length=300)
location_name = models.CharField(blank=True, max_length=300)
roundup_amount = models.DecimalField(max_digits=10, decimal_places=2, null=True)
transaction_date = models.DateField()
transaction_paid = models.BooleanField(default=False)
created_date = models.DateTimeField(auto_now=False, auto_now_add=True)
class MyUser(AbstractBaseUser):
username = models.CharField(max_length=255,unique=True,)
email = models.EmailField(verbose_name='email address',max_length=255,unique=True)
first_name = models.CharField(max_length=120,null=True,blank=True,)
last_name = models.CharField(max_length=120,null=True, blank=True,)
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
updated = models.DateTimeField(auto_now=True, null=True, blank=True)
答案 0 :(得分:2)
使用向后关系查询将做到:
MyUser.objects.filter(userbanktransaction_set__transaction_paid=False)
答案 1 :(得分:2)
如果您要检索用户ID列表:
let search_id = 2; // id to filter out
let list = Array.of(
{name: 'apple', id: 1},
{name: 'bread', id: 2},
{name: 'orange', id: 3},
{name: 'bagel', id: 4}
)
log({list});
let filtered = list.filter(e => e.id !== search_id)
log({filtered});
if (filtered.length)
log(`Found ${filtered.length} matches!`);
else
log(`The id of ${search_id} has not been found`);
// Simple logger so label is on its own line
function log(){
let [param1,...args]=arguments;
switch (typeof param1){
case 'string':
if (args.length)
console.log(`${param1}:`), // comma intentional
console.log(args.pop())
else
console.log(param1);
break;
case 'object':
for (let key in param1)
console.log(`${key}:`), // comma intentional
console.log(param1[key])
break;
default:
console.log('Error in passed arguments. Type not recognized.')
}
}
如果要检索用户对象列表:
UserBankTransaction.objects \
.filter(transaction_paid=False)\
.values_list('user', flat=True)
或者您可以在MyUser.objects.filter(userbanktransaction_set__transaction_paid=False)
中指定related_name
:
UserBankTransaction.user
然后您可以简单地执行以下操作:
class UserBankTransaction(models.Model):
user = models.ForeignKey(MyUser, related_name='bank_transactions')