Django onetoone relationship with User not working with query - python

My model is like this
class Profile(models.Model):
user = models.OneToOneField(User,default=None,null=True,on_delete=models.CASCADE)
name = models.CharField(max_length=50,null=True)
i am trying to get through models using shell but getting the empty query.
I tried this
>>> u1=User.objects.get(username='gautam')
>>>u1
<User: gautam>
>>> Profile.objects.get(user=u1)
Traceback (most recent call last):
File "/usr/lib/python3.6/code.py", line 91, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
File "/home/gautam/.local/lib/python3.6/site-
packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/gautam/.local/lib/python3.6/site-
packages/django/db/models/query.py", line 399, in get
self.model._meta.object_name
homes_login.models.DoesNotExist: Profile matching query does not
exist.
I am tring to get the user for that profile.

This profile is simply not created. Setting an OneToOne relation doesn't guarantee that profile will exist for each user. To overcome that, you should simply create new profile, like this:
>>> Profile.objects.create(user=u1)
To automate process of getting existing profile or creating new one, you can use get_or_create method.

Related

Saving model without writing to db in Django

I have a many-to-many to many type models. I use a script to populate the database. However I want to print the objects and save it only if i want it to be saved using a y/n style input. The problem is I can't create the objects without saving them as you can see below.
>>> mov = Movie(name="completenothing")
>>> direc = Director(name="Someone")
>>> direc.movie_name.add(mov)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 513, in __get__
return self.related_manager_cls(instance)
File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 830, in __init__
(instance, self.pk_field_names[self.source_field_name]))
ValueError: "<Director: Someone>" needs to have a value for field "id" before this many-to-many relationship can be used.
>>> direc.save()
>>> direc.movie_name.add(mov)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 934, in add
self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/home/username/Code/virtualenvironments/matrix/local/lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py", line 1060, in _add_items
(obj, self.instance._state.db, obj._state.db)
ValueError: Cannot add "<Movie: completenothing N/A>": instance is on database "default", value is on database "None"
>>> mov.save()
>>> direc.movie_name.add(mov)
Director and Movie are in a many-to-many relation and i want their information displayed before saving. Is there some mechanism to allow this ?
If you use a pre_save signal, you can try this.
from django.db.models.signals import pre_save
def confirm_save(sender, instance, **kwargs):
# do something with your instance (display information)
ans = input("Do you want to save(y/n)")
if ans == 'y':
print("Your instance saved successfully")
else:
raise Exception("Not saved")
pre_save.connect(confirm_save, sender=MyModel)

DB constantly exploding in Django

I am trying to get going with django, which so far I have found to be amazing other than repeated db issues.
My latest is following the Django by Example book and I have followed everything to the letter, yet when following some simple instructions to add some data via the python shell api I get the following:
>>> from django.contrib.auth.models import User
>>> from blog.models import Post
>>> user = User.objects.get(username='jamie')
>>> Post.objects.create(title='One More Post', slug='one-more-post', body='Post body', author='user')
Traceback (most recent call last):
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 69, in handle
self.run_shell(shell=options['interface'])
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/core/management/commands/shell.py", line 61, in run_shell
raise ImportError
ImportError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/query.py", line 346, in create
obj = self.model(**kwargs)
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/base.py", line 468, in __init__
setattr(self, field.name, rel_obj)
File "/Users/jamie/dev/venv/lib/python3.6/site-packages/django/db/models/fields/related.py", line 629, in __set__
self.field.rel.to._meta.object_name,
ValueError: Cannot assign "'user'": "Post.author" must be a "User" instance.
This has happened while following multiple tutorials and I am stumped. I followed standard instructions and installed, pip, python and django via terminal. Also using a virtual env so not sure why this is happening.
Use this instead of your statement.
Use user variable instead of 'user' string.
Post.objects.create(title='One More Post', slug='one-more-post',
body='Post body', author=user)

FieldError: Invalid field name(s) given in select_related: 'userinfo'. Choices are: userinfo

I get this error when trying to use only with select_related.
FieldError: Invalid field name(s) given in select_related: 'userinfo'. Choices are: userinfo
It's a little strange that it reports the field I'm trying to select as an error. Here is my query:
users_with_schools = User.objects.select_related('userinfo').only(
"id",
"date_joined",
"userinfo__last_coordinates_id",
"userinfo__school_id"
).filter(
userinfo__school_id__isnull=False,
date_joined__gte=start_date
)
I've been able to use select_related with only in other places in my code so I am not sure why this is happening.
Edit: Here is the full traceback
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "env/lib/python2.7/site-packages/django/db/models/query.py", line 138, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "env/lib/python2.7/site-packages/django/db/models/query.py", line 162, in __iter__
self._fetch_all()
File "env/lib/python2.7/site-packages/django/db/models/query.py", line 965, in _fetch_all
self._result_cache = list(self.iterator())
File "env/lib/python2.7/site-packages/django/db/models/query.py", line 238, in iterator
results = compiler.execute_sql()
File "env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 818, in execute_sql
sql, params = self.as_sql()
File "env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 367, in as_sql
extra_select, order_by, group_by = self.pre_sql_setup()
File "env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 48, in pre_sql_setup
self.setup_query()
File "env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 39, in setup_query
self.select, self.klass_info, self.annotation_col_map = self.get_select()
File "env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 203, in get_select
related_klass_infos = self.get_related_selections(select)
File "env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 743, in get_related_selections
', '.join(_get_field_choices()) or '(none)',
FieldError: Invalid field name(s) given in select_related: 'userinfo'. Choices are: userinfo
From the documentation:
All of the cautions in the note for the defer() documentation apply to only() as well. Use it cautiously and only after exhausting your other options.
...
Using only() and omitting a field requested using select_related() is an error as well.
select_related will try to fetch all the columns for userinfo. As described above, trying to restrict the set of columns to specific ones will result in an error - the combination of select_related and only does not support that.
It's probably worth noting the comment that goes with these methods:
The defer() method (and its cousin, only(), below) are only for advanced use-cases. They provide an optimization for when you have analyzed your queries closely and understand exactly what information you need and have measured that the difference between returning the fields you need and the full set of fields for the model will be significant.
Edit: you mention in a comment below that the following query, used elsewhere in your code, seems to work fine:
ChatUser.objects.select_related("user__userinfo").\
only( "id", "chat_id", "user__id", "user__username", "user__userinfo__id" )
My best guess is that you are hitting this bug in Django (fixed in 1.10).
I suppose the easiest way to verify is to check the SQL query generated by the queryset that seems to work. My guess is that you will find that it isn't actually querying everything in one go and that there are additional queries when you try to access the related model that you asked to be fetched in select_related.

Web2py built-in authentication, after filling in the username, email, etc it generates the following ticket

I am new to web2py, when I came around to use the built-in authentication, after filling in the username, email, etc it generates the following ticket.
I am a clueless to what to do! Any help would be really welcomed!
I am running a mac osx 10.8. Postgres 9.3.
The ticket
Traceback (most recent call last):
File "/Users/JoaoBtte/Documents/python/Hello/gluon/restricted.py", line 217, in restricted
exec ccode in environment
File "/Users/JoaoBtte/Documents/python/Hello/applications/Cifra/controllers/default.py", line 90, in <module>
File "/Users/JoaoBtte/Documents/python/Hello/gluon/globals.py", line 378, in <lambda>
self._caller = lambda f: f()
File "/Users/JoaoBtte/Documents/python/Hello/applications/Cifra/controllers/default.py", line 88, in user
return dict(form=auth())
File "/Users/JoaoBtte/Documents/python/Hello/gluon/tools.py", line 1297, in __call__
return getattr(self, args[0])()
File "/Users/JoaoBtte/Documents/python/Hello/gluon/tools.py", line 2554, in register
self.login_user(user)
File "/Users/JoaoBtte/Documents/python/Hello/gluon/tools.py", line 1976, in login_user
user = Row(user)
File "/Users/JoaoBtte/Documents/python/Hello/gluon/dal.py", line 6986, in <lambda>
__init__ = lambda self,*args,**kwargs: self.__dict__.update(*args,**kwargs)
TypeError: 'NoneType' object is not iterable
Do you have the following line in one of your model files (usually in db.py) ?
from gluon.tools import Auth
auth = Auth(db)
Could you show us your default.py controller?

changing django default model settings

I'm just starting with the django creating your own app tutorial (creating a Poll) I'm deviating slightly as I'm wanting to create an app using my own database model that already exists.
And in the tutorial it says
Table names are automatically
generated by combining the name of
the app (polls) and the lowercase
name of the model -- poll and choice.
(You can override this behavior.)
Primary keys (IDs) are added
automatically. (You can override
this, too.)
By convention, Django appends
"_id" to the foreign key field
name. Yes, you can override this,
as well.
But I can't see where it mentions how you can override this behaviour? I've defined my model as so
from django.db import models
# Create your models here.
class Channels(models.Model):
channelid = models.IntegerField()
channelid.primary_key = True
channelname = models.CharField(max_length=50)
Now when I go in to the shell this is what I get
>>> from tvlistings.models import *
>>> Channels.objects.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python26\lib\site-packages\django\db\models\query.py", line 67, in __
repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "C:\Python26\lib\site-packages\django\db\models\query.py", line 82, in __
len__
self._result_cache.extend(list(self._iter))
File "C:\Python26\lib\site-packages\django\db\models\query.py", line 271, in i
terator
for row in compiler.results_iter():
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py", line 67
7, in results_iter
for rows in self.execute_sql(MULTI):
File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py", line 73
2, in execute_sql
cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\util.py", line 15, in e
xecute
return self.cursor.execute(sql, params)
File "C:\Python26\lib\site-packages\django\db\backends\mysql\base.py", line 86
, in execute
return self.cursor.execute(query, args)
File "C:\Python26\lib\site-packages\MySQLdb\cursors.py", line 166, in execute
self.errorhandler(self, exc, value)
File "C:\Python26\lib\site-packages\MySQLdb\connections.py", line 35, in defau
lterrorhandler
raise errorclass, errorvalue
DatabaseError: (1146, "Table 'tvlistings.tvlistings_channels' doesn't exist")
Obviously it can't find the table tvlistings_channels as it's actually called channels. So how do I change the default?
You can override Model behavior in Django largely through the use of an inner Meta class
db_table allows you to rename the table name
specifying another field as the primary key will have it use that rather than a surrogate key (not in the Meta class, just in the model itself)
You should try and work your way all through the tutorial before you try and customise things. All these things are covered in the actual documentation, but it's best to have a basic understanding of things first before diving into that.
FWIW, here are the docs on defining your own primary key and specifying a table name. But really, do the tutorial as written first.

Categories

Resources