F
F
Friend2018-12-13 12:39:03
Django
Friend, 2018-12-13 12:39:03

What is the best way to build relationships between models in Django?

There is a main model "Spare part", it has fields that are associated with categories, models "Car brand, Car model, Modification, Engine".

  • A brand can have many models
  • The model has many modifications
  • The modification has many engines

That is, they are combined with a ForeignKey, and Spare Part can have it all. When editing in the Django admin panel, they are not merged, and if you link the Brand of the car to the spare part, then apart from the brand, I will not see anything else, and if you display the engine as the end point, you can see something like this:
Toyota | Mark 2 | GX61 | 1G-EU
Toyota | Mark 2 | GX61 | 1G-GEU
Toyota | Mark 2 | GX61 | 1G-GE
5c1227b8c5639143062364.png
Tell me how best to organize links between models and attach them to the "Spare"?
An example of what is:
from django.db import models
from django.utils.text import slugify
from time import time


class BrandCar(models.Model):
    name = models.CharField(max_length=50, verbose_name='Марка Авто')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "Марка"
        verbose_name_plural = "Марки"


class ModelCar(models.Model):
    name = models.CharField(max_length=50, verbose_name='Модель Авто')
    brand_car = models.ForeignKey('BrandCar', on_delete=models.CASCADE, verbose_name='Марка Авто')

    def __str__(self):
        return 'Марка: {}, Модель: {}'.format(self.brand_car, self.name)

    class Meta:
        verbose_name = "Модель"
        verbose_name_plural = "Модели"


class ModificationCar(models.Model):
    name = models.CharField(max_length=50, verbose_name='Модификация Авто')
    model_car = models.ForeignKey('', on_delete=models.CASCADE, verbose_name='')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "Модификация Авто"
        verbose_name_plural = "Модификации Авто"


class TypePart(models.Model):
    name = models.CharField(max_length=50, verbose_name='Тип Запчасти')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "Тип Запчасти"
        verbose_name_plural = "Тип Запчасти"


class EngineCar(models.Model):
    name = models.CharField(max_length=50, verbose_name='Двигатель Авто')
    modification_car = models.ForeignKey('ModificationCar', on_delete=models.CASCADE, verbose_name='Модификация')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "Двигатель"
        verbose_name_plural = "Двигателя"


def gen_slug(s):
    new_slug = slugify(s, allow_unicode=True)
    return new_slug + '-' + str(int(time()))


class SparePart(models.Model):
    name = models.CharField(max_length=50, verbose_name='Запчасть')
    number = models.CharField(max_length=50, verbose_name='Номер Запчасти', blank=True, )
    description = models.TextField(verbose_name='Описание', blank=True, )
    image = models.ImageField(upload_to='', verbose_name='Главное Изображение')
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='Цена')
    date = models.DateField(verbose_name='Дата')
    brand_car = models.ManyToManyField('BrandCar', verbose_name='Марка Авто')
    models_car = models.ManyToManyField('ModelCar', verbose_name='Модель Авто')
    modifications_car = models.ManyToManyField('ModificationCar', verbose_name='Модификация Авто')
    engines_car = models.ManyToManyField('EngineCar', verbose_name='Мотор/Двигатель')
    type_part = models.ForeignKey('TypePart', on_delete=models.CASCADE, verbose_name='Тип Запчасти')
    slug = models.SlugField(max_length=150, blank=True, unique=True)

    def save(self, *args, **kwargs):
        if not self.id:
            self.slug = gen_slug(self.name)
        super().save(*args, **kwargs)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['-date']
        verbose_name = "Запчасть"
        verbose_name_plural = "Запчасти"


class ImageCar(models.Model):
    image = models.ImageField(upload_to='')
    spare_part = models.ForeignKey('SparePart', on_delete=models.CASCADE, verbose_name='Изображение для Запчасти')

    def __str__(self):
        return '{}'.format(self.spare_part.name)

    class Meta:
        verbose_name = "Изображение"
        verbose_name_plural = "Изображения"

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question