P
P
PyChan2020-05-25 22:24:26
Django
PyChan, 2020-05-25 22:24:26

How to set value in label for ForeignKey in ModelForm by taking values ​​from specific column of child model?

I have 3 models:

class Cats(models.Model):
    id = AutoField(primary_key=True)
    name = CharField(max_length=150)
    LOC_CHOICES = [('nav', 'navigation panel'), ('main', 'mainpage'), ('footer', 'Footer')]
    location = CharField(max_length=150, choices=LOC_CHOICES, null=True, blank=True)
    objects = models.Manager()


class Marks(models.Model):
    id = AutoField(primary_key=True)
    name = CharField(max_length=150)
    objects = models.Manager()


class Items(models.Model):
    id = AutoField(primary_key=True)
    name = CharField(max_length=150)
    marks = ForeignKey(Marks, on_delete=models.DO_NOTHING)
    category = ForeignKey(Cats, on_delete=models.DO_NOTHING)
    price = DecimalField(max_digits=7, decimal_places=2)
    previous_price = DecimalField(max_digits=7, decimal_places=2)
    article_number = CharField(max_length=150)
    description = TextField()
    picture = CharField(max_length=500)
    objects = models.Manager()

And the corresponding form for Items:
class ItemsForm(ModelForm):
    class Meta:
        model = Items
        fields = ['name', 'marks', 'category', 'picture', 'article_number', 'price', 'previous_price']
        labels = {'marks': <тут надо что-то написать>, category: <тут надо что-то написать>
                  }

I need the selects for the marks and category fields to contain objects from child tables, but at the same time they would be signed not as <ModelName>, <ModelName> (1), etc., but as <content of the name column of the desired model> . I didn't find any documentation for this, so I would be very grateful if you could send me a link to the documentation or explain how to do it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-05-25
@PyChan

Are you talking about __str__ or something? https://docs.djangoproject.com/en/3.0/ref/models/i...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question