0

I have a question. I have a Bb model that includes the rubric and sub_rubric parameters. There are also Rubric and Sub_rubric models, one-to-many related. Question: how to link rubric and sub_rubric to each other in the Bb model, so that when a new instance of the Bb model is created, when the rubric changes, the subrubruc list changes too.

Code: 
class Rubric(models.Model):
    name = models.CharField(max_length=50, db_index=True)

   
class Sub_Rubric(models.Model):
    rubric = models.ForeignKey(Rubric, null=True, on_delete = models.PROTECT)
    name = models.CharField(max_length=50, db_index=True,  unique = True)
class Bb(models.Model):
   
    title = models.CharField(max_length=50)
    content = models.TextField(null=True, blank=True)
    price = models.FloatField(null=True,blank=True)
    published = models.DateTimeField(auto_now_add=True, db_index=True, )
    rubric = models.ForeignKey(Rubric, null=True, on_delete = models.PROTECT, related_name='name')
    sub_rubric = models.ForeignKey(Sub_Rubric, null=True, on_delete = models.PROTECT)
Daniil
  • 1
  • [link](https://pythonprogramming.net/foreign-keys-django-tutorial/) [link](https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_one/) [link](https://docs.djangoproject.com/en/3.2/topics/db/models/#relationships) These may help – ninjajosh5 Nov 11 '21 at 21:20

1 Answers1

0

In Bb you should only define a foreign key to sub_rubric. You can always get to Rubric via Sub_rubric.

Razenstein
  • 3,532
  • 2
  • 5
  • 17
  • If I do this, there is a very long sub_rubric list. Is it possible to make linked lists in django? – Daniil Nov 12 '21 at 05:03
  • I cant reply as it seems I do not entirely understand your problem. Maybe you add some more explanation. – Razenstein Nov 12 '21 at 06:05
  • In the admin panel, when I select one rubric from the list (for example, transport), the second list shows me all the sub_rubrics of all rubric (for example, when selecting rubric "transport", sub_rubric displays except "motorcycles , cars", also displays "studio apartment, house," and others). How to get around it? I hope I explained it clearly. – Daniil Nov 12 '21 at 07:30
  • ok - got it. maybe this helps: https://stackoverflow.com/questions/23664518/django-admin-filtering-foreignkey-dropdown-based-on-another-field – Razenstein Nov 12 '21 at 19:57
  • here is an example outside of admin: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html – Razenstein Nov 12 '21 at 20:03