class Project_types(models.Model):
project_type = models.CharField(max_length=200)
def __str__(self):
return self.project_type
class Projects(models.Model):
project_types = models.ForeignKey(Project_types, on_delete=models.CASCADE)
project = models.CharField(max_length=200)
def __str__(self):
return self.project
When I try to run Project_types(project_type='games').item_set.all()
I get an error saying that there is no attribute item set.
class Project_types(models.Model):
project_type = models.CharField(max_length=200)
def __str__(self):
return self.project_type
class Projects(models.Model):
project_types = models.ForeignKey(Project_types, on_delete=models.CASCADE)
project = models.CharField(max_length=200)
def __str__(self):
return self.project
First there's a few problems with your model.
First model names shouldn't be pluralized
Here a Projects (should be Project) has one project_type, and a Project_types (should be ProjectType) has one project.
To run the query you want:
Project_types.filter(project_type='games').item_set.all()
the correct query would be:
Project_types.filter(project_type='games').projects_set.all()
use projects instead of items,
the related manager is based on the Model name (in this case Projects becomes projects_set)
see here https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_one/
The .item_set attribute does not exist on the instance you have created by running:
Project_types(project_type='games')
It seems to me that you are trying to get all Projects of the type 'games'.
To do that, you'll have to use the QuerySet of the Projects class like this:
Projects.objects.filter(project_types__project_type='games').all()
Additionally, a suggestion: try to name all your model classes using singular CamelCase, so that they will be easier to understand. In your example, Project_types should be ProjectType, while Projects should be Project.
Project_types(project_type='games') doesn't actually return any object. That's why you got that attribute error. You need to add a filter or use get. Something like below:
Project_types.objects.get(project_type='games').item_set.all()
Or
Project_types.objects.filter(project_type='games').item_set.all()
Related
So I have 3 models which are chain connected to each other via ForeignKey and inside the Lesson model I want to create a file path to upload videos to like this courses/COURSE_NAME/SECTION_NAME, where uppercase letters are variables which should be replaced with the actual course name and section name, I don't have any problems with accessing the section name using section.name, but when I try to access the course name using the same approach section.course.name I get an error. Here is my models code:
class Course(models.Model):
name = models.CharField(max_length=80)
...
class Section(models.Model):
name = models.CharField(max_length=80)
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='sections')
...
class Lesson(models.Model):
name = models.CharField(max_length=80)
section = models.ForeignKey(Section, on_delete=models.CASCADE)
video = models.FileField(upload_to=f'courses/{section.course.name}/{section.name}/')
Error occurs in this part of code:
video = models.FileField(upload_to=f'courses/{section.course.name}/{section.name}/')
Here's the error message that I get:
video = models.FileField(upload_to=f'courses/{section.course.name}/{section.name}/')
AttributeError: 'ForeignKey' object has no attribute 'course'
Thanks in advance!!!
Edit 1:
So in process of thinking how to do this I came up with idea maybe there's a way to create a set_up method which will be run after the initialization of a course foreign key but before video file field. This set up method can treat self like you would treat an instance of a Lesson class so I tried to implement this using an __init__ method:
class Lesson(models.Model):
name = models.CharField(max_length=80)
section = models.ForeignKey(Section, on_delete=models.CASCADE)
section_id = None
def __init__(self, *args, **kwargs):
self.section_id = self.section.id
super(Lesson, self).__init__(args=args, kwargs=kwargs)
video = models.FileField(upload_to=f'courses/{section_id}/')
Project runs normally but when I go to the admin pannel and try to edit Lesson database server gives me this error:
'Lesson' object has no attribute '_state'
I did my research and found out that's because you can't just call an init method of models.Model. At least that's how I understood it.
Try doing this:
x = Lesson.objects.get(pk=1)
print('SECTION_NAME', x.section)
print('COURSE_NAME', x.section.course)
Update 19.12.2022
Based on the Lesson model and its pk, I tried to get data from the Section model, as follows, the first option with one value, the second with several:
aaa = Section.objects.filter(lesson__pk=1).all()
print('name', aaa)
print('course', aaa[0].course)
bbb = Section.objects.filter(lesson__pk__in=[1, 2]).all()
print('QuerySet more than one value', bbb)
for a in bbb:
print('id', a.id, 'course', a.course)
Update 24.12.2022
Perhaps the following will help you: pass the result returned by the function to upload_to.
def directory(instance, filename):
return '{0}/{1}/{2}'.format(instance.section.name, instance.section.course, filename)
class Lesson(models.Model):
name = models.CharField(max_length=80)
section = models.ForeignKey(Section, on_delete=models.CASCADE)
video = models.FileField(upload_to=directory, blank=True)
def __str__(self):
return self.name
I have a django project with a custom user model.
I have this Subscriptions model that uses the custom user model as its foreign key.
class Subscriptions(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
app_subscriptions = models.CharField(max_length=100)
def __str__(self):
return self.app_subscriptions
But if I try to retreive all users app_subscriptions with ..app_subscriptions_set.all() it always returns with the following error:
AttributeError: 'CustomUser' object has no attribute 'app_subscriptions_set'
I have the same type of model in use here:
from django.db import models
class Software(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Version(models.Model):
version = models.CharField(max_length=50)
software = models.ForeignKey(Software, on_delete=models.CASCADE)
def __str__(self):
return self.version
And on this model I have no issues querying for all software versions with ...version_set.last().
Anyone have any ideas? Thank you in advance.
Try using user_instance.subscriptions_set.all() instead of .app_subscriptions_set.all().
The default accesor is the model name, all lowercase, and appends _set. See the docs about it, or this question.
Your model Version is just like that:
software_instance.version_set.all()
Okay, so I have two Django models:
class Ticket(BaseModel):
name = models.CharField(max_length=200)
description = models.TextField(blank=True, null=True)
def get_absolute_url(self):
return '/core/group/ticket/{0}/'.format(self.id)
class ProjectTicket(Ticket):
project = models.ForeignKey('Project', on_delete=models.DO_NOTHING)
phase = models.ForeignKey('ProjectPhase', blank=True, null=True, on_delete=models.DO_NOTHING)
def get_absolute_url(self):
return '/different/url/structure'
Now, I'm querying all Ticket objects with Ticket.objects.all(). This will return all Ticket objects, including some that are ProjectTicket subclasses.
What I'd like to be able to do is access the subclass get_absolute_url() when the objects in question are actual subclassed ProjecTicket objects.
I know that I can get the parent class from the subclass, but I want to be able to do the reverse.
Has anyone achieved something like this? If so, what approach did you take?
Here's one way that I can think of right now:
I'm sure you know that inheriting django models creates a OneToOne relationship with the parent. So, the Ticket objects which are also instances of ProjectTicket class, will have an attribute called projectticket on them. You can check for this value and return the url accordingly:
class Ticket(...):
...
def get_absolute_url(self):
if hasattr(self, 'projectticket'):
return self.projectticket.get_absolute_url()
else:
return '/core/group/ticket/{0}/'.format(self.id)
In Django 1.8
class OtherModel(models.Model):
somefield = models.CharField(max_length=20)
class Orderform(models.Model):
sell_item_id = models.CharField(max_length=20)
class Selled(models.Model):
orderform = models.ForeignKey("Orderform")
sell_count = models.IntegerField()
something = OtherModel.objects.get(id=sell_item_id)
I need to use something like OtherModel.objects.get(id=sell_item_id).
How to get sell_item_id in class Selled(models.Model):?
You schema couldn't be presented in SQL.
Option #1:
class Orderform(models.Model):
sell_item_id = models.CharField(max_length=20)
othermodel = models.OneToOneField("OtherModel")
and get it
Selled.objects.get(pk=1).orderform.othermodel
Option #2:
class Selled(models.Model):
orderform = models.ForeignKey("Orderform")
sell_count = models.IntegerField()
def something(self):
return OtherModel.objects.get(id=self.sell_item_id)
and get
Selled.objects.get(pk=1).something()
But I think you should better think about you DB schema.
It looks like you have a couple of questions, for the first, to get the related
Selled.objects.filter(order_form__sell_item_id =id_to_get).select_related('order_form')
Notice the __ (double underscore) before sell_item_id. This is important because it says, selected Selleed by the sell_item_id of the OrderForm. and select_related makes sure that order form is brought back in the results with a single call to the db.
Now, if you want to do that for OtherModel, you will need to create a similar ForeignKey field in the OtherNodel and this will allow you to make the same query as above. Currently, you have no such relation.
class OtherModel(models.Model):
somefield = models.CharField(max_length=20)
orderform = models.ForeignKey("Orderform")
OtherModel.objects.filter(order_form__sell_item_id =id_to_get).select_related('order_form')
Don't forget to run:
python manage.py makemigration
python manage.py migrate
This should solve the issue.
I'm new to django and while the admin site is useful I need to be able to do simple functions without it. I would like to automatically manage my objects.
Is it possible to create objects outside of the admin site?
I know one way to do it
Class Foo (models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
def create(cls, name, url):
bar = cls(name=name)
return bar
s1 = Foo.create("THIS IS A NAME")
s1.save()
But I'm having trouble adding new variable to the object
How do I add unique variables to each object
thanks
Sorry I am not sure about your question. If you want to have a unique field for your model you can do
yourUniqueFieldName = models.TextField(max_length=100, unique=True)
And this for a pair of (or more) unique fields you can do
class Meta:
unique_together = ('field1', 'field2',)
Official documents is always your best friend as a start:
https://docs.djangoproject.com/en/dev/ref/models/fields/