简体   繁体   中英

Perform query with foreignkey django

I'm new to django and i've got this two django models. Now i'm trying to query the stripe in the second model(GenerateKeys) which has the Stripe as the foreignkey and the way i'm doing it is like this "

stripe.stripe_customer.all()

" so i can get the individual data from each user in the Stripe model and use it in the Generateakeys model. But i keep getting this error below

AttributeError: 'QuerySet' object has no attribute 'stripe_customer'

class Stripe(models.Model):
      user = models.OneToOneField(to=User, on_delete=models.CASCADE)
      CustomerId = models.CharField(max_length=255)

class GenerateKeys(models.Model):
    stripe = models.ForeignKey(Stripe,on_delete=models.CASCADE,related_name='stripe_customer')
    key_sha = models.CharField(max_length=255)

Thanks.

You're getting an attribute error because you're trying to access instance variables from a queryset.

First, get your instance, for the sake of the sake of example I will keep this easy.

You probably want to use some parameters to get your instance.

instance = stripe.first() # Get the first item in the queryset
customers = instance.stripe_customer.all()

If you want to get indiviual data of each model; loop over the queryset.

If the GenerateKeys model already has an instance, you could use annotations to get the data you need for each customer.

Example:

qs_annotated = GenerateKeys.objects.all()\
    .annotate(non_existant_field=models.F('stripe__user__username'))

And then you could access it like:

for inst in qs_annotated:
    print(inst.non_existant_field)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM