Home > Mobile >  Django model foreignkey or charfield?
Django model foreignkey or charfield?

Time:04-20

Django Model and Form that I want to make

Hello. I'm fairly new to Django and I have a hard time understanding which model field to use. I didn't post any code because my code is so messy right now and most of it still following "Django for Beginner" book by William S. Vincent.

I have an app consisting 2 models, Product model and Production model. Some fields on production model are linked to product model. Then from production model, I make a form for user input using ModelForm. (There's a link to an image to help understanding model and form relation.)

I have several questions regarding this matter.

  1. If I set product_id on Production Model as ForeignKey to Product, what field should I use for product_name and material?
  2. When I use CharField for both product_name and material, there are entry for both product_name and material on form and I don't want that. How to change it to readonly and have value updated based on product_id? (I'm not sure if this is related to Django form or not.)
  3. Right now I'm using ModelForm to make Production form and then using FormView to render the form. Is it the right approach? What is the difference between this one and CreateView from model?

Thank you in advance for any comments and answers.

CodePudding user response:

If you have a name and a material on the product model, you don't need those on the production model unless they relate to the production object. If I were you, I'd have a foreign key on Production to the product. It might look something like;

class Production(models.Model):
    product = models.ForeignKey(
        to=Product,
        verbose_name=_("Product"),
        on_delete=models.CASCADE
    )
    machine = models.CharField(
        verbose_name=_("Machine No"),
        max_length=255
    )
    date = models.DateTimeField(
        verbose_name=_("Date"),
        blank=True,
        null=True
    )

Then your form might be;

class ProductionForm(forms.ModelForm):
    class Meta:
        model = Production

        fields = (
            'product',
            'machine',
            'date',
        )

I would recommend using the django admin to get your models as you want them before you start working with views. If you know the data is being stored in a way you need, then you can worry about building the frontend. The admin is around page 70 of that book you've got. You can also do readonly fields with that.

  • Related