Django ORM select_related AttributeError - python

In my project im trying to use an external .py file for manage data using my django app style like this:
In my django project i create a model:
class temp_test_keywords(models.Model):
main_id = models.ForeignKey(temp_main)
test_id = models.ForeignKey(temp_case)
key_id = models.ForeignKey(temp_keywords)
variable_id = models.ForeignKey(temp_variables, null=True, blank=True)
def __str__(self):
return '%s -> %s' % (str(self.main_id), str(self.test_id))
Well, now in my external rst.py file i start django env like this:
import sys
import os
import django
sys.path.append('core')
os.environ['DJANGO_SETTINGS_MODULE'] = 'core.settings'
django.setup()
ok, at this point i import table and create class for do some thinks with it:
from django.db import models
from django.contrib.contenttypes.fields import
GenericForeignKey,GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db.models import Count
from frontend.models import temp_test_keywords
class PrepareRst:
def __init__(self,test_id,t_type,log=False):
self.rst = self.mainprep(test_id,t_type)
def mainprep(self,test_id,t_type):
return self.tc_prep(test_id)
#TestCase rst prep method
def tc_prep(self,test_id):
maxpar = temp_test_keywords.objects.filter(main_id = test_id).values('key_id').annotate(total=Count('variable_id')).order_by('-total').first()
totpar = maxpar['total']
#Part1 list creation
count = 0
ltouple = ()
l1 = ["Test Case"]
while (count < totpar):
l1.append("")
count += 1
ltouple += (l1,)
#Query for extract keywords, values
kv = temp_test_keywords.select_related()
but when i run an AttributeError: type object 'temp_test_keywords' has no attribute 'select_related' error raise
if i start python manage.py shell from terminal the "kv = temp_test_keywords.select_related()" command works fine, why in my .py code doesn't?
Thanks in advance

Try,
kv = temp_test_keywords.objects.all().select_related()

Related

Django model error with nested dictionaries

I am relatively new to Django, but not to python, My model is trying to use a class (defined in a separate file) in which data is coming from a REST API, the retrieved data is in a nested dictionary. The code will run fine in python, but when I try it in Django (makemigrations), I get an error:
File "c:\blah-blah\Clone_PR.py", line 20, in GetFoundOnSelectItems
values = self._issueEdit["fields"]["customfield_13940"]["allowedValues"]
TypeError: 'NoneType' object is not subscriptable
I tried using type hints, but that does not work either.
models.py
from dal import autocomplete
from django.db import models
from django.contrib import messages
from .Login import jlogin
from .Jira_Constants import ProductionServer, TestServer, StageServer
from .Clone_PR import Issue
jira = None
issue = Issue()
class ClonePrLogin(models.Model):
username = models.CharField(max_length=30)
password = models.CharField(max_length=30)
#classmethod
def LoginToJira(cls):
global jira
jira = jlogin(ProductionServer, cls.username, cls.password)
class PrEntry(models.Model):
prToClone = models.CharField(max_length=20)
#classmethod
def GetIssueAndMeta(cls):
global issue
issue.initialize(jira, cls.prToClone)
class ClonePr(models.Model):
issueKey = issue.issueKey
issue.GetFoundOnSelectItems()
foundOnList = issue.foundOnSelectItems
foundOn = autocomplete.Select2ListChoiceField(choice_list=foundOnList)
Clone_PR.py
from typing import List, Dict
class Issue():
def __init__(self):
self.jiraInst = None
self.issueKey = ''
self._issue = None
self._issueEdit = None
# self._issueEdit = Dict[str, Dict[str, Dict[str, List[Dict[str, str]]]]]
self.foundOnSelectItems = []
def initialize(self, jira, prKey):
self.jiraInst = jira
self.issueKey = prKey
self._issue = jira.issue(prKey)
self._issueEdit = jira.editmeta(prKey)
def GetFoundOnSelectItems(self):
values = self._issueEdit["fields"]["customfield_13940"]["allowedValues"]
items = [x["value"] for x in values]
self.foundOnSelectItems = items
In Django, running makemigrations will load all the modules. You said you're familiar with Python so you should know that the declarations inside the class:
class ClonePr(models.Model):
issueKey = issue.issueKey
issue.GetFoundOnSelectItems()
foundOnList = issue.foundOnSelectItems
foundOn = autocomplete.Select2ListChoiceField(choice_list=foundOnList)
will run when the modules load. You're calling issue.GetFoundOnSelectItems() at that time, which in turn calls values = self._issueEdit["fields"]["customfield_13940"]["allowedValues"], except that self._issueEdit = None upon the initiation of instance Issue above with this line: issue = Issue().
I highly recommend you spend some time to become more familiar with how Django starts up an app. The module-level and nested model declarations here are both antipatterns and may cause data issues in the future.

Django import-export of excel data

I'm using django import export (DIE) to import some data. I have a problem importing the data.
my admin.py:
class TestResource(resources.ModelResource):
class Meta:
model = Test
exclude = ('id',)
import_id_fields = ['VS',]
skip_unchanged = True
class TestAdmin(ImportExportMixin,admin.ModelAdmin):
fieldsets = [
('VS', {'fields':['VS']}),
('pool', {'fields':['pool']}),
('pool_port', {'fields':['pool_port']}),
('idc', {'fields':['idc']})
]
list_display = ('VS','pool','pool_port','idc')
list_filter = ['pool_port']
search_fields = ['VS','pool','pool_port','idc']
resource_class = TestResource
admin.site.register(Test,TestAdmin)
I want to import an excel file like:
But:
I want to import all the rows . Please tell me how to ignore the duplicates. Thanks in advance!
change line
skip_unchanged = True
to
skip_unchanged = False
OK I find one way to import. Import the file with save(). If you guys have a better way please tell me~
The code as follow:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE","mysite.settings")
import django
django.setup()
import xlrd
from Test.models import Test
def input(VS,pool_text,port,idc_text):
i = Test(
VS = vs,
pool = pool_text,
pool_port = port,
idc = idc_text
)
i.save()
files = xlrd.open_workbook('test.xls')
sh = files.sheet_by_index(0)
n = 0
for i in range(1,sh.nrows):
vs = sh.cell(i,0).value
pool_text = sh.cell(i,1).value
port = sh.cell(i,2).value
idc = sh.cell(i,3).value
input(vs,pool_text,port,idc)
n += 1
print n

django-cms default menu extend Menu or CMSAttachMenu?

I am trying to build a very simple, wiki-type site using django-cms.
I have 1 app, with 2 models defined:
class Subject(models.Model):
label=models.CharField
class Topic(models.Model):
...
cat = models.ForeignKey('topics.Category',
blank=True,
default=None,
help_text=u'Please choose a category for this topic',
null=True
)
I am trying to have the default menu show the Subject classes as the top-level options, with the Topic classes as sub-levels for each Subject. There will be 4 Subjects altogether. E.g.:
Subject 1
-topic1
-topic2
Subject 2
-topic3
-topic4
etc..
I have read all the django-cms docs, and I'm still confused. In my menu.py, should I be extending Menu or CMSAttachMenu? Do I need 4 different generators? How do I reference the ForeignKey field when using the generator?
I am a beginner, any help is greatly appreciated
You could do something like that:
# menu.py
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from cms.menu_bases import CMSAttachMenu
from menus.base import NavigationNode
from menus.menu_pool import menu_pool
from .models import Subject
class SubjectsMenu(CMSAttachMenu):
name = _("Subjects Menu")
def get_nodes(self, request):
nodes = []
cnt = 0
for subject in Subjects.objects.all():
subject_node_id = cnt
node = NavigationNode(
subject.label,
reverse('subject_view_detail', args=(subject.pk,)),
subject_node_id
)
nodes.append(node)
for topic in subject.topics.all():
cnt += 1
node = NavigationNode(
topic.name,
reverse('topic_view_detail', args=(topic.pk,)),
cnt,
subject_node_id # parent
)
nodes.append(node)
cnt += 1
return nodes
menu_pool.register_menu(SubjectsMenu)
Then you can add this menu to your AppHook or attach it from the admin.

Python evernote api Error

Trying to build app that connects with Evernote API, in Python/Django. For the below code i get the following error message: " 'Store' object has no attribute 'NoteFilter' " from http://dev.evernote.com/documentation/reference/NoteStore.html#Svc_NoteStore One can see, that NoteFilter is attribute of NoteStore.
def list(request):
nbname="mihkel's notebook"
client = EvernoteClient(token=token, sandbox=False)
note_store = client.get_note_store()
notebooks = note_store.listNotebooks()
for nb in notebooks:
if nbname == nb.name:
nb = nb
filter = note_store.NoteFilter()
filter.notebookGuid = nb.guid
notelist = note_store.findNotes(token,filter,0,10)
break
return render_to_response('list.html', {'nb': nb, 'notelist':notelist})
Solution:
from evernote.edam.notestore import NoteStore
....
....
def list.. :
...
Filter = NoteStore.NoteFilter()
notestore/ttypes.py has the definition for NoteFilter
Some of the examples in the API code import like this
import evernote.edam.notestore.NoteStore as NoteStore
import evernote.edam.type.ttypes as Types
Not sure if this would be an acceptable way to correct, but I added this:
import evernote.edam.notestore.ttypes as NoteStoreTypes
and created my filter like this:
filter = NoteStoreTypes.NoteFilter()

jinja2 Custom filter "TemplateAssertionError: no filter named 'format_number'"

I'm getting the "TemplateAssertionError: no filter named 'format_number'" error, when trying to register a custom filter on the template environment by updating the filters dict on the environment.
In my module, I have imported environment module as follows:
from jinja2 import environment
In my class I defined the following method:
class DashboardHandler(SecurePageHandler):
def format_number(number):
s = '%d' % number
groups = []
while s and s[-1].isdigit():
groups.append(s[-3:])
s = s[:-3]
return s + ','.join(reversed(groups))
def do_get(self):
# ... snip ...
env = environment.Environment(self)
env.filters['format_number'] = self.format_number
# ... snip ...
Inside my html template file I tried to implement the filter as follows:
{{top_five_url .total|format_number}}
How is this happening?
Is there a default environment instance, we should use?
I could resolve my problem as follow,
Inside the module, I defined my method and updated the filters dictionary globally as follows:
import jinja2
def format_number(number):
s = '%d' % number
groups = []
while s and s[-1].isdigit():
groups.append(s[-3:])
s = s[:-3]
return s + ','.join(reversed(groups))
jinja2.filters.FILTERS['format_number'] = format_number

Categories