Why am I still getting 'DeferredAttribute' object has no attribute 'objects'? - python

After a few days of searching, I still am unable to get over this hurdle. I'm just trying to print a list of descriptions from Sellers as a view. Here's what I'm working with...
models.py:
from django.db import models
class Sellers(models.Model):
index = models.BigIntegerField(blank=True, null=False)
seller = models.TextField(db_column='SELLER', blank=False, null=False,
primary_key=True)
block = models.TextField(db_column='BLOCK', blank=False, null=False)
street = models.TextField(db_column='STREET', blank=False, null=False)
space = models.TextField(db_column='SPACE', blank=False, null=False)
description = models.TextField(db_column='DESCRIPTION', blank=True, null=True)
document_with_idx = models.TextField(blank=False, null=False)
document_with_weights = models.TextField(blank=False, null=False)
class Meta:
managed = False
db_table = 'Sellers'
def __str__(self):
return self.index
'''
views.py:
from django.http import HttpResponse
from search.models import Sellers
def search(request):
output = Sellers.description.objects.all()
return HttpResponse(output)
'''
Any direction would be appreciated, I feel like I've read every related post related to this. Figured it was about time to post a question with my exact setup. Thanks!

Sellers.description refers to the field, so you get basically the TextField object, not one of the descriptions of an object, since Sellers is a class, not a Sellers object. You can obtain the description values with:
from django.http import JsonResponse
from search.models import Sellers
def search(request):
output = Sellers.objects.values_list('description', flat=True)
return JsonResponse({'data': list(output)})
Furthermore you can not simply wrap that in a HttpResponse, since that expects a string/bytes-like object. You can for example JSON encode it with a JsonResponse.

Related

many to many field error __call__() missing 1 required keyword-only argument: 'manager'

error image
I'm using the model and I keep running into problems with many to many. At first, I made it without giving an id value, but it seems that the id value is not entered, so when I put the id value directly, the same problem as above occurs. But in the Post model below, the same form of likes is used. Why?
from django.db import models
# from django.contrib.auth.models import User
from django.conf import settings
# from server.apps.user.models import Profile
# Create your models here.
class Clothes(models.Model):
CATEGORYS =[
(0, '상의'), #상의
(1, '하의'), #하의
(2, '아우터'), #아우터
(3, '신발'), #신발
(4, '악세사리'), #악세사리
]
category = models.IntegerField(default=0,choices=CATEGORYS)
id = models.IntegerField(primary_key=True)
img = models.ImageField(upload_to='main/images/clothes/%Y/%m/%d')
save = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Pickitems', blank=True)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
buying = models.TextField(null=True, blank=True)
def __str__(self):
return f'{self.id}: {self.category}'
#pk가 존재하지 않는것 같음.
# class SavePeople(models.Model):
class Post(models.Model):
main_img = models.ImageField(upload_to='main/images/post/%Y/%m/%d')
title = models.CharField(max_length=100)
content = models.TextField()
private = models.BooleanField(default=False)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
clothes = models.ManyToManyField(Clothes,related_name='Clothes')
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Likes', blank=True)
def __str__(self):
return f'{self.pk}: {self.title}'
def get_absolute_url(self):
return f'/community/'
#이거 나중에 detail page로 바꿔주세요
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
content = models.TextField()
create_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f'({self.author}) {self.post.title} : {self.content}'
class Commu(models.Model):
COMMU_CHOICES = [
('buying', 'buying'), #공동구매
('openrun', 'openrun'), #오픈런
('question', 'question'), #고민방
]
category = models.CharField(max_length=20, choices=COMMU_CHOICES)
img = models.ImageField(upload_to='main/images/commu/%Y/%m/%d', null=True, blank=True)
title = models.CharField(max_length=100)
content = models.TextField()
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return f'{self.pk}: {self.title}'
def get_absolute_url(self):
return f'/community/commu'
I added the code saves= models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='Save', blank=True) to the Clothes model to make a save of Clothes in the same way as the likes of the Post model, but an error like the attached picture is displayed. occurred. When I searched, it seemed that the pk value did not exist.
The issue is the id field that you explicitly provided, Django itself creates an id field as a primary key for each model if you don't specify one. So, it is not necessary to add it to the model. Kindly remove it through the Clothes model and run migration commands.
And it doesn't give in case of likes since there is no extra field id in Post model unlike that of Clothes.
Note: Models in Django doesn't require s to be added as suffix, as it is automatically done, so you may change Clothes to Cloth.

Django Rest Framework, Serializer Level Filter

I have two models named Account and Story. With the help of a models.Manager on Django, I wrote a method that retrieves the stories posted in the last 24 hours. With Django, this method works very well. The problem is that when I create a serializer with Django Rest Framework it pulls all the stories. To prevent this, I wrote a method called get_image_file and used the method I wrote with the help of models.Manager here, but I could not solve the problem. As a result, how do I pull only the stories that were posted in the last 24 with Django Rest Framework, as I did on the Django side?
serializers.py
from rest_framework import serializers
from ..models import Account, Story
class StorySerializer(serializers.ModelSerializer):
class Meta:
model = Story
fields = ['image_file']
def get_image_file(self, obj):
#This method doesn't work. DRF pulls all the stories.
return obj.get_available_stories()
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = '__all__'
stories = StorySerializer(many=True)
models.py
from django.db import models
import datetime
def upload_to(instance, filename):
username = instance.account.username
return '%s/%s/%s' %('stories',username,filename)
def upload_pp(instance, filename):
return '%s/%s/%s' %('profile_photo', instance.username,filename)
class Account(models.Model):
username_pk = models.CharField(max_length=122)
username = models.CharField(max_length=55, unique=True)
profile_photo_id = models.CharField(max_length=155, unique=True)
profile_photo = models.ImageField(upload_to=upload_pp, null=True, blank=True)
profile_photo_width = models.IntegerField(null=True, blank=True)
profile_photo_height = models.IntegerField(null=True, blank=True)
def __str__(self):
return self.username
class StoryManager(models.Manager):
def get_available_stories(self, *args, **kwargs):
date_from = datetime.datetime.now() - datetime.timedelta(days=1)
return super(StoryManager, self).filter(image_timestamp__gte = date_from)
class Story(models.Model):
account = models.ForeignKey(to=Account, on_delete=models.CASCADE, related_name="stories")
image_file = models.ImageField(upload_to=upload_to, blank=True, null=True, editable=False)
image_url = models.URLField()
image_pk = models.CharField(max_length=60, null=True, blank=True, editable=False, unique=True)
image_timestamp = models.DateTimeField(null=True, blank=True)
image_width = models.IntegerField(null=True, blank=True)
image_height = models.IntegerField(null=True, blank=True)
objects = StoryManager()
def __str__(self):
return str(self.account)
An way to do that is using Filters Class.
Works very similar as Serializer class.
Custom Generic Filter
def filter_queryset(self, request, queryset, view):
# Override this method to do your filtering.
# Probably your BaseModel has some filed as created_at
# Assuming that is a Datetime object
return queryset.filter(created_at.hour__lte=24)
# You can even sort this values adding a .sort_by() after the filter

Field 'id' expected a number but got <Listing: Ps4 Pro>

It's my first time creating a Django website with models, and in my first attempt to insert data into my table I'm getting this error.
My models are as follows:
class User(AbstractUser):
pass
#https://docs.djangoproject.com/en/3.1/topics/auth/default/
class Listing(models.Model):
listingID = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="listID")
created_by = models.ForeignKey(User, on_delete=models.SET_NULL, related_name="myListing", null=True)
watchers = models.ManyToManyField(User, blank=True, related_name="watchlist")
title = models.CharField(max_length=30)
description = models.TextField()
creation_date = models.DateField(auto_now=True)
img_url = models.URLField()
active = models.BooleanField(default=True)
def __str__(self):
return f"{self.title}"
class Bid(models.Model):
listing = models.ForeignKey(Listing, on_delete=models.SET_NULL, related_name="bidsMadeOnMe", null=True, blank=True)
user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name="myBids", null=True)
price = models.FloatField()
creation_date = models.DateField(auto_now=True, null=True)
def __str__(self):
return f"Bid={self.price}"
and the view that handles the form submission is this one:
#login_required
def create_listing(request):
if request.method == "POST":
user = User.objects.get(username=request.user.username)
l = Listing(created_by=user,
title=request.POST["title"],
description=request.POST["desc"],
# https://stackoverflow.com/questions/12176585/handling-dates-over-request-get
creation_date=models.DateTimeField(auto_now_add=True),
img_url=request.POST["image_url"]
)
l.save()
b = Bid(l,
user,
request.POST["initial_bid"],
models.DateTimeField(auto_now_add=True)
)
b.save()
return render(request, "auctions/index.html")
I know the problem is the way I'm adding the data but I can't fix it. Can someone give me some light?
Your problem (well, several actually) is this:
b = Bid(l, user, request.POST["initial_bid"], models.DateTimeField(auto_now_add=True))
You're constructing a model instance by positional arguments instead of keyword arguments. This can be done, but then the invisible "id" column that has been added to the Bid model, is the first argument.
In Django we never construct models like that, but always use keyword arguments, so we're not depending on field order:
b = Bid(listing=l, user=user, ...))
Once you're solved that, your next problem is the date field.
Don't assign fields to model instances. Fields are class declarations, they don't belong on instances. Fields describe on a class (= a Model), what kind data to expect. On the instance, you assign that data.
In this case, your definition for the field is wrong on the model and on the instance you shouldn't even assign it - it will be automatically filled.
Overall, it feels like you haven't gone through Django's tutorial or did not fully understand the concepts. I suggest you go through it.

'Registered_Courses' object has no attribute 'course_set' Django

I am really stuck on this error and it does not make sense why it does not follow the relationship backward on Registered_Courses on the foreign key for Courses when i use course_set
views.py
def registered_coursesView(request, username):
'''Page to display the registered courses of a user.'''
registeredCourses = Registered_Courses.objects.get(owner = request.user)
courseInfo = registeredCourses.course_set.all()
context = {'registeredCourses': registeredCourses, 'courseInfo':courseInfo}
return render(request, 'safetyCourseApp/registered_courses.html', context)
models.py
class Course(models.Model):
'''Offered Course information.'''
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
name = models.CharField(max_length=200, primary_key=True)
description = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
start_date = models.DateField()
end_date = models.DateField()
price = models.DecimalField(max_digits=10, decimal_places=2)
capacity = models.IntegerField()
registered_ppl = models.IntegerField()
def __str__(self):
"""Return a string representation of the model."""
return self.name
class Registered_Courses(models.Model):
"""Something specific learned about a Course."""
registered_course = models.ForeignKey(Course, on_delete=models.CASCADE, null=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
def __str__(self):
"""Return a string representation of the model."""
return f'{self.owner}'
Please let me know what you guys think. I cannot think of a reason why this is not working. Thanks!
As you have specified in your models, each Registered_Courses will have a FK to Course, So each Course can have multiple Registered_Courses.
But you are trying to get multiple Course objects from a single Registered_Courses
The backward relationship is something like:
>>> course = Course.objects.first()
>>> course.registered_courses_set

Showing form within another one

I want to show a form within another form.
For example I have these models:
class Measure(models.Model):
length = models.ForeignKey(Statistics, related_name='Length', null=True, blank=True)
surface_area = models.ForeignKey(Statistics, related_name='Surface area+', null=True, blank=True)
section_area = models.ForeignKey(Statistics, related_name='Section area+', null=True, blank=True)
volume = models.ForeignKey(Statistics, related_name='Volume', null=True, blank=True)
diameter = models.ForeignKey(Statistics, related_name='Diameter', null=True, blank=True)
class Statistics(models.Model):
total = models.FloatField('Total', null=True, blank=True)
avg = models.FloatField('Average', null=True, blank=True)
min = models.FloatField('Minimum', null=True, blank=True)
max = models.FloatField('Maximum', null=True, blank=True)
standard_deviation = models.FloatField('Standard deviation', null=True, blank=True)
and then I have these forms corresponding to the previous models:
class StatisticsForm(forms.ModelForm):
class Meta:
model = Statistics
fields = '__all__'
class MeasureForm(forms.ModelForm):
class Meta:
model = Measure
fields = '__all__'
# Here I have to say that the right form for each field is the StatisticForm
The ForeignKey in the forms is rendered as a combo box includes all the objects in the other table (in my case the Statistics table), I want to replace the combo box with an object of StatisticsForm so I can control the way I render the Statistics objects
Thank you very much.
Your database scheme and models are incorrectly designed to solve the problem at hand. You are defining a "has many" relationship in the wrong direction. One Measurement is supposed to have several Statistics, however one Statistics is not supposed to have many Measurement.
As your models are set up right now the ForeignKey is on the wrong side of the relationship. You should do this instead:
class Measure(models.Model):
def save(self,*args,**kwargs):
result = super(Measure, self).save(*args,**kwargs)
Statistics.objects.create(name='length', measurement=self)
Statistics.objects.create(name='section', measurement=self)
Statistics.objects.create(name='surface', measurement=self)
Statistics.objects.create(name='volume', measurement=self)
Statistics.objects.create(name='diameter', measurement=self)
return result
To provide the same comfort in accessing the Statisticss for one Measurement as in your current code you can add a couple of #property shortcuts:
class Measure(models.Model):
#property
def length(self):
return self.statistics_set.get(name='length')
#property
def section(self):
return self.statistics_set.get(name='section')
#property
def surface(self):
return self.statistics_set.get(name='surface')
#property
def volume(self):
return self.statistics_set.get(name='volume')
#property
def diameter(self):
return self.statistics_set.get(name='diameter')
class Statistics(models.Model):
name = models.CharField(max_length=10)
measurement = models.ForeignKey('Measurement')
total = models.FloatField('Total', null=True, blank=True)
avg = models.FloatField('Average', null=True, blank=True)
min = models.FloatField('Minimum', null=True, blank=True)
max = models.FloatField('Maximum', null=True, blank=True)
standard_deviation = models.FloatField('Standard deviation', null=True, blank=True)
Once you fix the relationship between the objects the problem becomes much easier to solve. Instead of being ForeignKeyFields in the form, the Statisticss become proper related objects, which are routinely handled by django.
As #solarisssmoke mentioned in the comments you are looking for formsets. Here is an example from the django documentation showing how to achieve what you need:
The models in question:
class Author(models.Model):
name = models.CharField(max_length=100)
title = models.CharField(max_length=3, choices=TITLE_CHOICES)
birth_date = models.DateField(blank=True, null=True)
def __str__(self): # __unicode__ on Python 2
return self.name
class Book(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
And a view using inlineformset_factory to create the needed formset:
from django.forms import inlineformset_factory
def manage_books(request, author_id):
author = Author.objects.get(pk=author_id)
BookInlineFormSet = inlineformset_factory(Author, Book, fields=('title',))
if request.method == "POST":
formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
if formset.is_valid():
formset.save()
# Do something. Should generally end with a redirect. For example:
return HttpResponseRedirect(author.get_absolute_url())
else:
formset = BookInlineFormSet(instance=author)
return render(request, 'manage_books.html', {'formset': formset})
If performance becomes an issue also have a look at prefetch_related for boosting performance.

Categories

Resources