Django create nested model - django

I want to create a Model in which I can store the same models as for example in a folder there can be several folders.
I tried like this:
class Service(models.Model):
name = models.TextField(default="")
price = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.name
class ServiceType(models.Model):
services_types = models.ManyToManyField(ServiceType, null=True, blank=True)
services = models.ManyToManyField(Service, null=True, blank=True)
name = models.TextField(default="")
But it didn't work. How can this problem be solved?

If you want to reference same model then you have to use quotation 'ModelName' like this.
So your code will be like:
class Service(models.Model):
name = models.TextField(default="")
price = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.name
class ServiceType(models.Model):
services_types = models.ManyToManyField('ServiceType', null=True, blank=True)
services = models.ManyToManyField(Service, null=True, blank=True)
name = models.TextField(default="")

Related

calling a class inside another class function

I am trying to create an educational website using django so I have a class model and a course model. I have tried to use the Many-to-one foreignkey relationship but that doesn't work, I can create classes using foreignkey but that class is not being assigned to that course only. It appears in other courses as well. So how can I make this work? What should I change?
My models.py:
class Class(models.Model):
title = models.CharField(max_length=100)
video = models.FileField(upload_to='class/class_videos',null=True,
validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])])
def __str__(self):
return self.title
class Course(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='class/instructor_pics', null=True)
instructor = models.CharField(max_length=100)
instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True)
students = models.ManyToManyField(User, related_name='courses_joined', blank=True)
classes = models.ForeignKey(Class, on_delete=models.CASCADE, null=True)
slug = models.SlugField(max_length=200, unique=True)
description = models.TextField(max_length=300, null=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
def __str__(self):
return self.title
You are using the foreign key in the wrong model. If each class can only have one course, but a single course, can have multiple classes, you should place the ForeignKey in the class model instead of the course model. Your code would be like this:
class Course(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(upload_to='class/instructor_pics', null=True)
instructor = models.CharField(max_length=100)
instructor_image = models.ImageField(upload_to='class/instructor_pics', null=True)
students = models.ManyToManyField(User, related_name='courses_joined', blank=True)
slug = models.SlugField(max_length=200, unique=True)
description = models.TextField(max_length=300, null=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
def __str__(self):
return self.title
class Class(models.Model):
title = models.CharField(max_length=100)
video = models.FileField(upload_to='class/class_videos',null=True,
validators=[FileExtensionValidator(allowed_extensions=['MOV','avi','mp4','webm','mkv'])])
course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, related_name='classes')
def __str__(self):
return self.title
And when you want to list the classes of a single course, you can use this code (you should use the related_name field in the source model like the way I have used in the class model):
course = Course.objects.filter(some_filter=some_value).first()
course.classes.first() # This will return the first class of the course

possible to split the model based on field in DRF admin.py

I have model named organization. I am using this same model model for 2 api's. I have a field code. one API do code auto generation another API takes user entry code. I want to separate the tables based on code. Autogeneration code starts SUB001,SUB002,.... like wise. user entry code thats userwish.
models.py
class Organization(models.Model):
code = models.CharField(max_length=255, null=False, unique=True)
name = models.CharField(max_length=255, null=False)
organization_type = models.CharField(max_length=255, choices=TYPES, null=False, default=COMPANY)
internal_organization = models.BooleanField(null=False, default=True)
location = models.ForeignKey(Location, on_delete=models.RESTRICT)
mol_number = models.CharField(max_length=255, null=True, blank=True)
corporate_id = models.CharField(max_length=255, null=True, blank=True)
corporate_name = models.CharField(max_length=255, null=True, blank=True)
routing_code = models.CharField(max_length=255, null=True, blank=True)
iban = models.CharField(max_length=255, null=True, blank=True)
description = models.TextField(null=True, blank=True)
total_of_visas = models.IntegerField(null=False, default=0)
base_currency = models.ForeignKey(Currency, on_delete=models.RESTRICT, null=True, blank=True, default=None)
logo_filename = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
def __str__(self):
return self.name
admin.py
#admin.register(Organization)
class OrganizationAdmin(admin.ModelAdmin):
list_display = (
'id',
'code',
'name',
'location',
'organization_type',
'internal_organization',
'mol_number',
'corporate_id',
'corporate_name',
'routing_code',
'iban',
'description',
'total_of_visas',
'base_currency',
'logo_filename',
)
Is there any possible to split models based on code,.. Really Expecting help...
You can use Proxymodel inheritance. Documentation
class AutoGenerationManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(code__istartswith="SUB")
class AutoGeneration(Organization):
objects = AutoGenerationManager()
class Meta:
proxy = True
class UserGenerationManager(models.Manager):
def get_queryset(self):
return super().get_queryset().exclude(code__istartswith="SUB")
class UserGeneration(Organization):
objects = UserGenerationManager()
class Meta:
proxy = True

Restrict choices using two foreignkey relationships in django

I have three models, a household model, a household-member model, and an occupations models as described below. I would like the occupations model to only show members that belong to a particular household (which is related to field sno). How does one do something like this?
Would be grateful for any help.
class Household(models.Model):
village = models.CharField(max_length=150, null=True, blank=True)
household_number = models.IntegerField(blank=True, null=True)
form_number = models.IntegerField(null=True,blank=True)
head_of_household = models.CharField(max_length=150, null=True, blank=True)
class member(models.Model):
sno = models.ForeignKey(Household, on_delete=models.CASCADE)
person_number = models.IntegerField(blank=True, null=True)
name = models.CharField(max_length=150, null=True, blank=True)
sex_choices2 = (
('M','Male'),
('F','Female'),
)
sex = models.CharField(max_length=3,choices=sex_choices2,blank=True, null=True)
age = models.CharField(max_length=30,blank=True, null=True)
class Meta:
unique_together = (("sno", "person_number"),)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class occupations(models.Model):
sno = models.ForeignKey(Household,on_delete=models.CASCADE)
person_number = models.IntegerField(blank=True, null=True)
name = models.ForeignKey(member, blank=True, on_delete=models.SET_NULL, null=True)
occupation = models.CharField(max_length=100, null=True, blank=True)
class Meta:
unique_together = (("sno", "person_number","occupation"),)

Name error: Can not import [model name]

I am trying to link the model Post to the model Topic via a foreign key. When I run the makemigrations command, it raises an import error, and says that the name 'Topic' is not defined. What could be the cause of this? It certainly seems to be defined. I've pretty much ruled out that it is not a problem within the db.
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
title = models.CharField(max_length=100)
summary = models.TextField(blank=True, null=True)
content = models.TextField()
draft = models.BooleanField(default=False)
details = models.CharField(blank=True, null=True, max_length=250)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
topic = models.ForeignKey(Topic, blank=True, null=True)
thumbnail = models.ImageField(upload_to='media', blank=True, null=True)
def get_absolute_url(self):
return reverse('posts:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.title
class Topic(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
picture = models.ImageField(upload_to='media', blank=True, null=True)
isperson = models.BooleanField(default=False)
ispolicy = models.BooleanField(default=False)
positive = models.BooleanField(default=True)
percent = models.CharField(max_length=5)
def __str__(self):
return self.name
Any ideas? I don't see any problems in this code, and neither did my IDE, which recognized the model Topic
I am considering that you have indented your code for Post model properly in your file.
Solution : Try to define Topic above Post.
First, this
topic = models.ForeignKey(Topic, blank=True, null=True)
should be this
topic = models.ForeignKey('Topic', blank=True, null=True)
This way it tells django that you're setting a foreign key to a model, which isn't declared yet, but will be declared further in the code.
Second, you should properly indent your Post model and its methods:
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
title = models.CharField(max_length=100)
summary = models.TextField(blank=True, null=True)
content = models.TextField()
draft = models.BooleanField(default=False)
details = models.CharField(blank=True, null=True, max_length=250)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
topic = models.ForeignKey('Topic', blank=True, null=True)
thumbnail = models.ImageField(upload_to='media', blank=True, null=True)
def get_absolute_url(self):
return reverse('posts:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.title
Because as you have it now, django doesn't understand that the unindented fields belong to the Post model.

django EAV filtering

I have the following models.
class Category(MPTTModel):
name = models.CharField(max_length=100, null=False, blank=False)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
def __unicode__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=250, null=False, blank=False)
category = models.ForeignKey('Category')
price = models.DecimalField(decimal_places=2, max_digits=7)
def __unicode__(self):
return self.name
class ProductAttribute(models.Model):
products = models.ManyToManyField('Product')
category = models.ForeignKey('Category')
property = models.CharField(max_length=250, null=False, blank=False)
value = models.CharField(max_length=250, null=False, blank=False)
I need to be able to select products based on a given category, and a given attribute.
For example, if I have the product "Blender", I want to select all blenders within a given category, with a given attribute (such as brand = black & decker).