L
L
lehubozedo2017-08-22 15:29:02
Django
lehubozedo, 2017-08-22 15:29:02

How to make the model refer to itself?

Preamble:
There are 3 models:
Potato, Eggplant, Tomato
And there is one connecting model - Vegetable (it is for the online store catalog, because there can be different goods in the basket, and on the main one, here it is used everywhere, you can say the proxy model ( without proxy attribute),

class Veggies(models.Model):
   tomato = models.OneToOneField(Tomato, verbose_name='Томат', on_delete=models.CASCADE, blank=True, null=True)
    ...

Essence of the question:
I need to attach gifts to the Vegetable model (it is clear that this is an abstraction), the same vegetable.
A reference to itself is not something, because There may be multiple gifts.
Let the tomato, potato, eggplant refer to a vegetable? or how else is it possible? Help plz.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
lehubozedo, 2017-08-24
@lehubozedo

All done in one line

gifts = models.ManyToManyField('self', blank=True, symmetrical=False)

A
Artyom Belousov, 2017-08-22
@flygrounder

If you need to attach a vegetable to a vegetable, then you should think about the fact that a vegetable + a gift is already a different abstraction, which means a different model

P
Pavel Shvedov, 2017-08-22
@mmmaaak

Create a second table: id, vegetable_id, vegetable_gift_id. Make vegetable_id and vegetable_gift_id pair unique

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question