How can I know the query when doing a .get queryset in django
I have this model:
class Artist(EsIndexable, models.Model):
name = models.CharField(max_length=50)
birth_date = models.DateField()
And I did this in the shell:
x = Artist.objects.get(name="Eminem")
print x.query
Then I got the error:
AttributeError: 'Artist' object has no attribute 'query'
.get returns an instance, not a queryset.
To see the query that is done, do the same thing but with .filter, which does return a queryset:
queryset = Artist.objects.filter(name="Eminem")
print queryset.query
x = queryset.get()
from django.db import connection
x = Artist.objects.get(name="Eminem")
print connection.queries[-1]
Related
I am trying to insert some data into MySQL database (model LogsSeparate) through Django and Django Rest Framework but I keep getting an error which I bet is very easy to solve yet I couldn't figure it out myself:
Error:
if obj.pk is None:
AttributeError: 'LogObjTest' object has no attribute 'pk'
Code:
class LogObjTest():
def __init__(self):
self._id = None
self.bits = None
class getLogs(viewsets.ModelViewSet):
arrayTest=[]
for x in Logs.objects.all():
serializer_class = LogsSeparateSerializer
test = Fields.objects.filter(pac_id=x.message_id_decimal)
binaryTest=x.data_binary
for i in test:
obj=LogObjTest()
obj._id=x.message_id_decimal
obj.bits=binaryTest[i.fld_offset:i.fld_offset+i.fld_len]
arrayTest.append(obj)
queryset = arrayTest
LogsSeparate.objects.bulk_create(arrayTest)
print("arrayTest",arrayTest)
models.py
class LogsSeparate(models.Model):
_id = models.CharField(max_length=255, primary_key=True, null=False, db_column='_id')
bits = models.CharField(max_length=500, db_column='bits')
def __str__(self):
return self.bits```
Don't use LogObjTest. Import LogsSeparate that you created in the model.py file then use it to create a new object.
class getLogs(viewsets.ModelViewSet):
arrayTest=[]
for x in Logs.objects.all():
serializer_class = LogsSeparateSerializer
test = Fields.objects.filter(pac_id=x.message_id_decimal)
binaryTest=x.data_binary
for i in test:
obj=LogsSeparate(_id=x.message_id_decimal, bits=binaryTest[i.fld_offset:i.fld_offset+i.fld_len])
arrayTest.append(obj)
queryset = arrayTest
LogsSeparate.objects.bulk_create(arrayTest)
print("arrayTest",arrayTest)
I'm trying to query a specific column from my table. I've tried doing it with this
team_lenDeserialized = RolesInTeam.objects.values_list('user_id', flat=True).filter(academic_year_id=9).filter(deleted=0)
team_lenDict = RolesInTeamSerializer(team_lenDeserialized, many=True)
team_len = orderedDictToJSON(team_lenDict.data)
After that I run it through a function that converts it to JSON
def orderedDictToJSON(orderedDict):
return json.loads(json.dumps(orderedDict))
then I go and manipulate it further. However if I try to serialize and convert the team_lenDeserialized I get an error that states
AttributeError: Got AttributeError when attempting to get a value for field `user_id` on
serializer RolesInTeamSerializer`.
The serializer field might be named incorrectly and not match any
attribute or key on the `int` instance.
Original exception text was: 'int' object has no attribute 'user_id'.
This is my model for that table
class RolesInTeam(models.Model):
user_id = models.IntegerField()
team_id = models.IntegerField()
role_id = models.IntegerField()
deleted = models.IntegerField()
academic_year_id = models.IntegerField()
class Meta:
managed = False
db_table = 'roles_in_team'
and my serializer
class RolesInTeamSerializer(serializers.ModelSerializer):
class Meta:
model = RolesInTeam
fields = ['id', 'user_id', 'team_id', 'role_id', 'deleted', 'academic_year_id']
I have no clue what's happening or why it's not working.
You can only serialize models instances with a ModelSerializer, and values_list() returns a queryset of tuples, so when you try to use the serializer over the queryset, you get the error.
If you make a regular query (team_lenDeserialized = RolesInTeam.objects.filter(academic_year_id=9).filter(deleted=0)), you would be able to serialize team_lenDeserialized.
Assuming I have model and custom manager like this:
class FooManager(models.Manager):
def get_query_set(self):
super(FooManager, self).get_query_set()
class Foo(models.Model):
name = models.CharField(max_length=10)
status = models.BooleanField(default=False)
objects = FooManager()
I feel like this should be pretty simple but looked through documentation and "self" probably I missed something obvious. My question is how I can return object/queryset depending on lookups passed during actual query?
For example:
objs = Foo.objects.all()
print(objs, "Objects queryset only with status set to True")
objs = Foo.objects.filter(name__icontains='a')
print(objs, "Objects queryset with 'a' in name and status set to True")
objs = Foo.objects.filter(name__icontains='a', status=False)
print(objs, "Objects queryset with 'a' in name and status set to False")
I could imagine something looks like this sample:
class FooManager(models.Manager):
def get_query_set(self):
status = self.passed_lookups['status']
queryset = super(FooManager, self).get_query_set()
if status is None:
queryset = queryset.filter(status=True)
else:
queryset = queryset.filter(status=status)
return queryset
queryset of manager class has no access to query passed to it.
you can do this by creating two query manager class for your model. see below
class FooManager(models.Manager):
def get_query_set(self):
super(FooManager, self).get_query_set().filter(status=True)
class Foo(models.Model):
name = models.CharField(max_length=10)
status = models.BooleanField(default=False)
objects = FooManager()
all_objects = models.Manager()
in your code you must use Foo.objects.filter when you want to filter status and use Foo.all_objects when you dont want to filter status
I got this error message if I'm using SQL statement to populate data in dropdown.
Error message
'RawQuerySet' object has no attribute 'all'
Model.py
#python_2_unicode_compatible # only if you need to support Python 2
class FacebookAccount(models.Model):
user = models.ForeignKey(User)
account_description = models.CharField(max_length=50)
facebook_application_id = models.CharField(max_length=50)
facebook_application_secret = models.CharField(max_length=50)
ouath_token = models.CharField(max_length=500)
status = models.BooleanField(default=False)
def __str__(self):
return self.account_description
#python_2_unicode_compatible # only if you need to support Python 2
class FacebookFanPage(models.Model):
facebook_account = models.ForeignKey(FacebookAccount)
fan_page_description = models.CharField(max_length=50)
fan_page_id = models.CharField(max_length=30)
fan_page_access_token = models.CharField(max_length=500, null=True)
def __str__(self):
return self.fan_page_description
class Campaign(models.Model):
aList = (
('1', 'Send replies to inbox messages'),
('2', 'Post replies to users comments')
)
user = models.ForeignKey(User)
campaign_name = models.CharField(max_length=50)
autoresponder_type = models.CharField(max_length=10, choices=aList, null=True)
facebook_account_to_use = models.ForeignKey(FacebookAccount)
set_auto_reply_for_fan_page = models.ForeignKey(FacebookFanPage)
message_list_to_use = models.ForeignKey(PredefinedMessage)
#reply_only_in_this_hourly_interval
reply_only_for_this_keyword = models.CharField(max_length=50, null=True)
View.py
def autoresponder_create(request, template_name='autoresponder/autoresponder_form.html'):
if not request.user.is_authenticated():
return redirect('home')
form = AutoresponderForm(request.POST or None)
form.fields["set_auto_reply_for_fan_page"].query = FacebookFanPage.objects.raw('SELECT * '
'FROM fbautoreply_facebookfanpage '
'JOIN fbautoreply_facebookaccount ON fbautoreply_facebookfanpage.facebook_account_id = fbautoreply_facebookaccount.id '
'WHERE fbautoreply_facebookaccount.user_id = %s ', [str(request.user.id)])
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
form.save()
return redirect('autoresponder_list')
return render(request, template_name, {'form':form})
As the first comment says it seems like you are calling all() on queryset. You dont have to call .all() after executing raw sql queries, if you are assigning that to a variable since that variable already includes all objects fetched by your query.
In [6]: t = Team.objects.raw('SELECT * FROM core_team')
In [7]: t
Out[7]: <RawQuerySet: SELECT * FROM core_team>
In [8]: t[0]
Out[8]: <Team: test>
In [9]: [x for x in t ]
Out[9]: [<Team: test>, <Team: team2>, <Team: adminTeam>, <Team: team4>]
and if you call t.all()
In [11]: t.all()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-11-2ce0015f044f> in <module>()
----> 1 t.all()
AttributeError: 'RawQuerySet' object has no attribute 'all'
In [12]:
So it seems like you are calling all() on after executing a sql raw query. Remove that piece of code and it will be solved.
You can refer to this section of django docs if you want to use better ways to execute a sql query.
Edit
Try changing form.fields["set_auto_reply_for_fan_page"].query to form.fields["set_auto_reply_for_fan_page"].queryset
you can create view in sql or select query
then
you can manupulete this query with raw sql
for example you want to make filter with like contidion.
firs select all joining table with view or select
the query is first query slect all
new query is manuplulated query with raw.
not: select syntax for postgressql
if request_post:
if request_post.get('name'):
name = request_post.get('name')
name = '%'+name+'%'
condition = "WHERE account_name like"
s = '%s'
new_query = f"""{query} {condition} {s} """
queryset=TestOrderDetail.objects.raw(new_query,[name] )
form.fields["set_auto_reply_for_fan_page"].choices = [(None, '---'),] + [ (x.id, x.name ,) for x in FacebookFanPage.objects.raw('''select id, name from dual''')]
Hello Guy I'm a newbie to Django. Im using Rest API with Django to interact with my android application. I have the data I need in variable quest. Since there are multiple questions I'm using filter instead of get.
This is my Views.py:
class MapertablesViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Mapertables.objects.all()
serializer_class = MapertablesSerializer
lookup_field = 'category_id'
def get_queryset(self):
#print self.kwargs['category_id']
maps = Mapertables.objects.filter(category_id=self.kwargs['category_id'])
#queryset = list(maps)
#queryset = serializers.serialize('json',maps)
#print "AAAA ",queryset
i = 0
#quest ={}
queryset = []
queslist = []
for question in maps:
quest = {}
quest['question'] = question.question_id
#print 'qqqq ',question.question_id
#queryset = serializers.serialize('json',[question,])
choices = Choice.objects.filter(question=question.question_id)
print choices
#aaa = chain(question,choices)
#print aaa
#queryset = serializers.serialize('json',[question,choices,])
j = 0
for option in choices:
quest[j] = option.choice_text
j += 1
print 'data Here ',quest
#data Here {0: u'Highbury', 1: u'Selhurst Park', 2: u'The Dell', 3: u'Old Trafford', 'question': <Question: At which ground did Eric Cantona commit his "Kung Fu" kick ?>}
serializer_class = CoustomeSerializer(queryset, many=True)
print serializer_class.data
#[]
json = JSONRenderer().render(serializer_class.data)
print 'JSON',json
#[]
i += 1
queryset = queslist
serializer_class = CoustomeSerializer(queryset,many=True)
return queryset
#print "questions",queslist
#print "Ser ",ser.data
This is my serializers.py:
class MapertablesSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Mapertables
fields = ('question_id','category_id')
class CoustomeSerializer(serializers.HyperlinkedModelSerializer):
#questions = MapertablesSerializer(source='question_id')
#choices = ChoiceSerializer(source='choice_text')
class Meta:
model = Question,Choice,Category
fields = ('choice_text','choice_text','choice_text','choice_text','question_id')
URL that is defined to show:
http://127.0.0.1:8000/mapers/
Exception Type: KeyError
Exception Value: 'category_id'
when I query for a specific category it returns:
http://127.0.0.1:8000/mapers/2/
{
"detail": "Not found."
}
Model.py file is as follows:
from django.db import models
# Create your models here.
class Category(models.Model):
category_name = models.CharField(max_length=200,default='1')
def __str__(self):
return self.category_name
class Question(models.Model):
question_text = models.CharField(max_length=200)
#category_name = models.ForeignKey(Category)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
def __str__(self):
return self.question_text
class Mapertables(models.Model):
category_id = models.ForeignKey(Category)
question_id = models.ForeignKey(Question)
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
I want to get all questions related to category and there choices form the choices module that why all the stuff in get_queryset.
Please tell me how to get all the data required for me in MapertablesViewSet class
Thank You in advance if you want me to send the complete project just let me know and I will make zip and upload it to a drive or something.
#Kevin Brown is right you shouldn't worry about the serializers, or rendering anything on the get_queryset method, but a thing I noticed in your get_queryset method is that you don't append any item to the lists queryset, and querylist. I'm giving you an idea below:
def get_queryset(self):
#print self.kwargs['category_id']
maps = Mapertables.objects.filter(category_id=self.kwargs['category_id'])
i = 0
queryset = []
for question in maps:
quest = {}
quest['question'] = question.question_id
choices = Choice.objects.filter(question=question.question_id)
print choices
j = 0
for option in choices:
quest[j] = option.choice_text
j += 1
print 'data Here ',quest
# Adding items to queryset list
queryset.append(quest)
i += 1
# You should have values here on queryset list
print queryset
return queryset
As to the URL, be sure you are passing the category_id as a parameter on the URL pattern. Something like url(r'^mapers/(?P<category_id>\d+)/?', if you are not using routers for this. It would be good if you paste here your URLs definition. Well, I hope it helps you to have a better idea how to continue.
You are returning an empty list from your get_queryset method, so no objects are being returned in the list view and a specific object cannot be retrieved by the pk.
You appear to be doing a lot of unrelated things in your get_queryset method, and they are probably contributing to this issue. You shouldn't be doing any serialization there, DRF will handle that for you later. And you should be doing filtering in the filter_queryset method, or passing that off to DRF to do. You also can't return any responses from that method, only a queryset.