O
O
organica2019-11-09 21:31:37
Django
organica, 2019-11-09 21:31:37

ForeignKey to specific model field, how?

Gentlemen programmers, tell me how can I make the oneToMany relation through ForeignKey, binding not to a specific model, but to its field?

class TechType(models.Model):
    type_name = models.CharField(max_length=100, verbose_name='Вид техники', unique=True)

    def __str__(self):
        return self.type_name


class TechUnit(models.Model):
    inner_id = models.CharField(max_length=100, verbose_name='Внутренний номер', unique=True)
    tech_type = models.ForeignKey(TechType, on_delete=models.CASCADE, verbose_name='Вид техники')

    def __str__(self):
        return self.inner_id

First of all, I create 4 instances of the TechType class.
Next, I create instances of the TechUnit class: I enter its Inner_id and select from the drop-down list what type of equipment it belongs to in TechType. The choice is normal, exactly those categories of equipment that I started in the previous step appear in the drop-down list.
However, then I started to catch errors related to casting text to a string and for a long time could not understand what the reason was, until I accidentally created a new TechType called 4 and the error disappeared. My template loaded and gave me the information I needed. Climbed into the database and found an interesting thing (see screenshot). My TechUnit in the DB is bound to the id TechType, not the field TechType type_name. For example, a TechUnit with inner_id 114 is bound to a TechType Pallet_truck, but in the database it is bound to tech_type_id = 4. How do I bind to the type_name field of the TechType class???
5dc705c73b3a7158919268.jpeg

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dr. Bacon, 2019-11-10
@bacon

You have trouble understanding relationships, ForeignKey is bound to model id. Your wishlist doesn't make sense.

D
Denis BotViber, 2019-11-10
@cellmon

Or if there are not many dozens of class objects - two! In general, eliminate the TechType model
and in the TechUnit model, fill in the tech_type field through choises

class TechUnit(models.Model):
    type_name1 = 'номер1'
    type_name2 = 'номер2'
    type_name3 = 'номер3'
    Category = [
        ( type_name1, 'номер1'),
        ( type_name2, 'номер2'),
        ( type_name3, 'номер3'),
    ]
    inner_id = models.CharField(max_length=100, verbose_name='Внутренний номер', unique=True)
    tech_type = models.CharField(max_length=100, verbose_name='Вид техники', choices=Category, 
                default=Main) 
   def __str__(self):
        return self.inner_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question