简体   繁体   中英

Using One Model inside another model in Django

I am Developing a E-commerce Application with Django

So what I was thinking is getting the category of the Product in a separate Model and list them down in another using choice field in CharField.

So Here is the code for this

This is the model for getting the Categories from the user

class ProjektCat(models.Model):
    id = models.AutoField(primary_key=True)
    Option_Name = models.CharField(max_length=50)
    Option_Number = models.IntegerField()
    Number_Visits = models.IntegerField(default=0)

    def __str__(self):
        return f'{self.Option_Name}'

and here is the code to list those categories as a dropdown in the CharField

class Software_And_Service(models.Model):
    id = models.AutoField(primary_key=True)
    Product_Name = models.CharField(max_length=100, default='')
    projectKats = ProjektCat.objects.all()
    choice = []
    for i in projectKats:
        option = (i.Option_Number, i.Option_Name)
        choice.append(option)
    Cateogary = models.CharField(
        max_length=256, choices=choice)
    Price = models.IntegerField(default=0)
    Description = models.TextField(default='', max_length=5000)
    pub_date = models.DateField(auto_now_add=True, blank=True, null=True)
    image = models.URLField(default='')
    linkToDownload = models.URLField(default='')

    def __str__(self):
        return f'Projekt : {self.Product_Name}'

But it's Showing me an Error that there is no such table in app_name .projektcat

Is there is any solution for this??

It's not how you do this. First correctly assign the projectKats field ie

# You can set max_length as per your choice
projectKats = models.CharField(max_length=50)

You need to do this logic in django forms rather than django models.

So this is how you can do it.

forms.py

from django import forms
from .models import ProjektCat, Software_And_Service


def get_category_choices():
    return [(obj.Option_Name,obj.Option_Name) for obj in ProjektCat.objects.values_list('Option_Name',flat=True).distinct()]


class SoftwareAndServiceForm(forms.ModelForm):
    projectKats = forms.ChoiceField(choices=get_category_choices)

    class Meta:
        model = Software_And_Service
        fields = [
                  'projectKats',
                   # whatever fields you want
                 ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM