Unidirectional association

19 views
Skip to first unread message

Manos Zeakis

unread,
Feb 26, 2020, 9:35:00 AM2/26/20
to Django users
Hi all

I have created two classes. Instances of class A are timeless and instances of class B are different each year. Each instance of class B is associated with an instance of class A.

So I suppose I should do something like this

class A(models.Model):
    name = models.CharField(max_length=20, default = 'null')

class B(models.Model):
    A = models.ForeignKey('A', on_delete=models.CASCADE, related_name = "bs")
   
Now I need to declare three fields on class A that point to a different instance of class B for current, past and next year
    current_B
    previous_B
    next_B

I cannot find a way to declare such an association. Could you help me?

Thank you

Naveen Arora

unread,
Feb 27, 2020, 12:55:52 AM2/27/20
to Django users
Hi Manos,

Kindly explain the scenario appropriately, What exactly are you trying to achieve? Also read - https://docs.djangoproject.com/en/3.0/topics/db/examples/many_to_many/

Cheers,
Naveen Arora

Manos Zeakis

unread,
Feb 27, 2020, 3:16:10 AM2/27/20
to Django users
Thank you

I finally made it. I was afraid about circular references and DB possible corruptions, but Django seems to be resilient and surprises me all the time.

What I did was

1. Declared three different ForeignKeys from class A to B
2. Chose PROTECT instead of CASCADE for on_delete
3. Let blank/null True
4. Of course chose three different related_names

Naveen Arora

unread,
Feb 28, 2020, 7:19:56 AM2/28/20
to Django users
great. Happy to help :)

Cheers
Reply all
Reply to author
Forward
0 new messages