-
Notifications
You must be signed in to change notification settings - Fork 15
Description
I'm having some weird behaviors when trying to use a one-to-one relationship and I'm not sure if this is a bug or if I am doing something wrong.
Let's say I have the following models:
class Tenant(AbstractTenant):
name = models.CharField(max_length=50)
def natural_key(self):
return (self.name, )
class A(TenantModel):
name = models.CharField(max_length=30)
class B(TenantModel):
main = models.OneToOneField(A)
name = models.CharField(max_length=40)
And I try to run the following on the django shell:
from core.models import Tenant, A, B
t, _ = Tenant.objects.get_or_create(name='tenant1')
a_model = A.for_tenant(t)
a_model.objects.filter(b__name='test')
Then I get an exception: django.core.exceptions.FieldError: Cannot resolve keyword 'b' into field. Choices are: id, name
If I try to access this reverse relationship directly through an instance of A with something like a_model.objects.first().b
, then I get this exception: django.db.utils.ProgrammingError: relation "core_b" does not exist LINE 1: ...b"."id", "core_b"."main_id", "core_b"."name" FROM "core_b" W...
But if I simply access the tenant model for B in this shell session with b_model = B.for_tenant(t)
then things start behaving differently:
Running a_model.objects.filter(b__name='test')
now gets me django.core.exceptions.FieldError: Cannot resolve keyword 'b' into field. Choices are: b_set, id, name
, which says to me that there is now a b_set
relationship (but I think it should be named b
only, since this is an OneToOneField
) and I can filter it with no errors with a_model.objects.filter(b_set__name='test')
. It should be noted that before accessing the B
tenant model the same command does not work at all.
Other similar strange behaviors happen when I try to access b_set
on an A
instance before running B.for_tenant(t)
.
It seems that this affects ForeignKey
fields also, but I just looked briefly at it.
Am I missing something? I am using Django 1.10.2, by the way.
Thanks!