Accessing Model Data In Another Model/form
Hello i have created a simple model and now i want to access the data in another model to view it later on. My model looks like this: from django.db import models class A(models.Mo
Solution 1:
Django allows you to create class methods using @classmethod decorator. You can use that to pass data from first model into second model. Take a look at example below.
First model:
from django.db import models
class A(models.Model):
asd = models.CharField(max_length=50,default="DEFAULT VALUE")
def __str__(self):
return(self.asd)
# This is important
@classmethod
def get_all_choices(cls):
# I still suggest you to go through Django documentation
# to understand what query sets are
return cls.objects.values_list('asd', flat=True)
Second model:
from django.db import models
from a.models import A
class B(models.Model):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.choice_array = A.get_all_choices()
choices = models.CharField(max_length=10, choices=self.choice_array)
Please observe the comments. If you need to understand how to import A into B, refer to this question - Django : Unable to import model from another App
I have done this a couple of times but don't have the setup in hand to try. There might be some errors which you need to resolve on your own by reading the error messages.
Post a Comment for "Accessing Model Data In Another Model/form"