What is wrong in these lines:
for i in message_list:
message_stream = Messages.objects.filter(OrderID = i.OrderID).order_by('-MessageLocalID')
if message_stream[0].MessageTypeName != 'MessageAck':
message_stream[0].status = message_stream[0].MessageTypeName
message_stream[0].save()
The status field doesn't get saved here in the DB. What I do misunderstand here?
The problem was in the DB itself, the status field, where it should be updated with new values,wasn't able to receive values more than 2 characters. I used Django DB migration and extended the status field, solved the problem.
This command worked like a charm with no problems:
NpMessages.objects.filter(NPOrderID = i.NPOrderID, MessageTypeName = 'Request').update(status = message_stream[1].MessageTypeName)
and get rid of the save statement, as it didn't work eitherway!!!
Related
I'm making a django website and due to the load on the database I'd like to filter the queryset after retrieving it.
files = Files.objects.get(folder_id=folder_id)
first_file = files.objects.filter(sequence = 0)
This example throws me error, same if I tried for loop. So is it possible to filter the retrieved queryset without interacting with database ?
when you run get that executes the query, returns a single Files object. https://docs.djangoproject.com/en/4.1/ref/models/querysets/#get
you would want to change the first line to filter (which won't actually execute the query yet)
https://docs.djangoproject.com/en/4.1/ref/models/querysets/#filter
and the second line to get.
files = Files.objects.filter(folder_id=folder_id)
first_file = files.objects.get(sequence = 0)
I have been struggling with this simple query in django. I have checked a lot over internet. I tried using similar syntax - yet no luck.
In my application on html page I need to display some specific record. And for that i want to use parameterized select statement. But the query is not working..
I have checked id2 is getting correct value from previous html page..
And I know I can use APIs but for my databases classes I need to use raw queries in my application.
Can someone please help me here...
def details(request, id2):
temp = 'test3'
data = Posts.objects.raw('''select * from posts_posts where posts_posts.id = %s ''', id2)
context ={
'post' : data,
If you run that code you will see an error, since that is not the correct format for a call to raw. If you can't see the error output anywhere, then you have yet another problem for another post.
The correct format for raw is: .raw(sql, iterable-values), like this:
posts = Posts.objects.raw("select * ..", [id2, ]) # or use (id2,) for a tuple
<RawQuerySet: select * from ... where id = 5>
To get the actual list, since that just gives you a Query, you need to evaluate it somehow:
posts_list = list(posts)
first_post = posts[0]
Be careful, if you don't evaluate the QuerySet then it can be re-run a second time. Please convert it to a list() before doing further operations on it.
There were a similar question here Gensim Doc2Vec Exception AttributeError: 'str' object has no attribute 'words', but it didn't get any helpful answers.
I'm trying to train Doc2Vec on 20newsgroups corpora.
Here's how I build the vocab:
from sklearn.datasets import fetch_20newsgroups
def get_data(subset):
newsgroups_data = fetch_20newsgroups(subset=subset, remove=('headers', 'footers', 'quotes'))
docs = []
for news_no, news in enumerate(newsgroups_data.data):
tokens = gensim.utils.to_unicode(news).split()
if len(tokens) == 0:
continue
sentiment = newsgroups_data.target[news_no]
tags = ['SENT_'+ str(news_no), str(sentiment)]
docs.append(TaggedDocument(tokens, tags))
return docs
train_docs = get_data('train')
test_docs = get_data('test')
alldocs = train_docs + test_docs
model = Doc2Vec(dm=dm, size=size, window=window, alpha = alpha, negative=negative, sample=sample, min_count = min_count, workers=cores, iter=passes)
model.build_vocab(alldocs)
Then I train the model and save the result:
model.train(train_docs, total_examples = len(train_docs), epochs = model.iter)
model.train_words = False
model.train_labels = True
model.train(test_docs, total_examples = len(test_docs), epochs = model.iter)
model.save(output)
The problem appears when I try to load the model:
screen
I tried:
using LabeledSentence instead of TaggedDocument
yielding TaggedDocument instead of appending them to the list
setting min_count to 1 so no word would be ignored (just in case)
Also the problem occurs on python2 as well as python3.
Please, help me solve this.
You've hidden the most important information – the exact code that triggers the error, and the error text itself – in the offsite (imgur) 'screen' link. (That would be the ideal text to cut & paste into the question, rather than other steps that seem to run OK, without triggering the error.)
Looking at that screenshot, there's the line:
model = Doc2Vec("20ng_infer")
...which triggers the error.
Note that none of the arguments as documented for the Doc2Vec() initialization method are a plain string, like the "20ng_infer" argument in the above line – so that's unlikely to do anything useful.
If trying to load a model that was previously saved with model.save(), you should use Doc2Vec.load() – which will take a string describing a local file path from which to load the model. So try:
model = Doc2Vec.load("20ng_infer")
(Note also that larger models might be saved to multiple files, all starting with the string you supplied to save(), and these files must be kept/moved together to again re-load() them in the future.)
I am trying to set my model form with data as well as initial_dict. They both are working fine indivisiually, but when i put both in the method call, Initial does not work.
here is the code.
state = Territory.objects.filter(abbreviation=request.GET.get('territory', ''))
if state:
initial_dict['state'] = state.get()
ctx['add_customer'] = AddCustomer(data=request.GET, initial=initial_dict)
But the state (Dropdown) does not get selected.
This works fine
ctx['add_customer'] = AddCustomer(initial=initial_dict)
Ideas?
This is actually solved my problem.
initial_dict = request.GET.dict()
state = Territory.objects.filter(abbreviation=initial_dict.get('state', ''))
if state:
initial_dict['state'] = state.get()
ctx['add_customer'] = AddCustomer(initial=initial_dict)
Converted data to Python Dict & use only Initial.
I am still not sure why that problem was occurring.
Calling UserModel.objects.filter(email__iexact=email) results in the following query
SELECT * FROM "accounts_person" WHERE "accounts_person"."email" = UPPER('my-email#mail.com')
This doesn't find anything because it there's no EMAIL#MAIL.COM in the database, only email#mail.com. Shouldn't the query have been translated to
WHERE UPPER("accounts_person"."email") = UPPER('my-email#mail.com')?
Summary:
UserModel.objects.filter(email=email) # works
UserModel.objects.filter(email__exact=email) # works
UserModel.objects.filter(email__iexact=email) # doesn't work
Clash you ae right this i also faced the same situtaion with postgres sql .
If you go through This ticket
You will get some idea .
Perhaps an option could be passed to EmailField to state whether you want it to lower all case or not. It would save having to do something in the form validation like.
def clean_email(self):
return self.cleaned_data['email'].lower()
My bad. I had patched lookup_cast to be able to use the unaccent module on postgresql and ended up not calling the original lookup_cast afterwards. The generated query now looks like this WHERE UPPER("accounts_person"."email"::text) = UPPER('my-email#mail.com'). This is the default behavior on django.