I have this model:
class Order(Model):
sale_address = ForeignKey(Address)
purchase_address = ForeignKey(Address)
and want to conditionally annotate one address or another depending on some condition, as a ForeignKey:
order = Order.objects.annotate(
address=... # sale_address if current user is seller
).first()
assert isinstance(order.address, Address) # True
How can I do that?
I've tried this:
annotate(
address_id=Case(
When(
user_role='SELLER',
then=F('sale_address'),
),
When(
user_role='BUYER',
then=F('purchase_address'),
),
),
)
but in this case address_id is just an integer and I get N+1 issues when making list of orders with address.region.