Home > Enterprise >  how to get the foreignkey attribute value
how to get the foreignkey attribute value

Time:11-07

I'm trying to print out the email related to a specific OrderItem for a Customer, I've followed the logic from the answer below and I get the terminology but I'm definitely missing something, can't figure out what exactly, as of now I get the error name 'email' is not defined

#Models

class Customer(models.Model):
    email = models.EmailField(max_length=150)

class Order(models.Model):
    customer = models.ForeignKey(Customer)

class OrderItem(models.Model):
    object_one = models.CharField(max_length=300)
    object_two= models.BooleanField(default=False)


#View

@receiver(pre_save, sender=OrderItem)
def order_item_pre_save(instance, *args, **kwargs):
    if instance.object_one is not None and instance.object_two==True:

        customer_email = OrderItem.objects.filter(order__customer__email=email)
        print(customer_email)

        print(instance.object_one)
    else:
        print("object_one not provided")

#Traceback

Exception Type: NameError at /admin/main/order/126/change/
Exception Value: name 'email' is not defined

CodePudding user response:

There can be multiple OrderItems for such customer. You filter with:

def test():
    email = '[email protected]'
    customer_email = OrderItem.objects.filter(order__customer__email=email)
    print(customer_email)

If you have an OrderItem object you use:

myorderitem.order.customer.email
  • Related