0

I have a situation where I have 2 models, with the second model (B) being a subclass of the first (A), and also having a (different) 1-to-1 reference to another instance of same parent model (A). The objective is to have some special cases of A linked to other instances of A's in a new table, B's. For reasons I won't get into here, these need to be 2 different models (ie I can't add a nullable 1-to-1 reference field on A). This is illustrated below.

class A(models.Model):
    name = models.CharField()

class B(A):
    reference = models.OneToOneField(A)

However now when I try instantiate B with a reference to a different A, it doesn't work. Consider the following:

>>> a1 = A(name='a1')
>>> a1.save()
>>> b1 = B(name='b1', reference=a1)
>>> b1.save()
>>> b1.id
1
>>> b1.reference.id
1

Or alternatively:

>>> a1 = A(name='a1')
>>> a1.save()
>>> b1 = B(name='b1')
>>> b1.save()
>>> b1.reference = a1
>>> b1.save()
>>> b1.id
2
>>> b1.reference.id
2

Whereas what I would like here is for b1.id to equal 2 and b1.reference.id to equal 1 (referencing a1).

What is going on here? Why can't I have independent references to the base instance with the ptr_id and a different entry in the same table, in the reference field?

Maps
  • 135
  • 10
  • you can assign the value of `b1.refrence_id = 1`, but make sure that there is an instance in table `A` with id=1. – Nalin Dobhal Mar 17 '20 at 09:18
  • Hi @NalinDobhal, my apologies please see the edits, with the reference being a 1-to-1 association. It works with an FK, but I want to enforce 1-to-1. I can get it to work by changing the relationship to FK and enforcing uniqueness of the reference, but was wondering why it doesn't work with a OneToOneField – Maps Mar 17 '20 at 10:58

0 Answers0