python


Extract OneToOne Field in django model


class Post(models.Model):
created_time = models.DateTimeField()
comment_count = models.IntegerField(default=0)
like_count = models.IntegerField(default=0)
group = models.ForeignKey(Group)
class MonthPost(models.Model):
created_time = models.DateTimeField()
comment_count = models.IntegerField(default=0)
like_count = models.IntegerField(default=0)
group = models.ForeignKey(Group)
post = models.OneToOneField(Post)
I use this two models. MonthPost is part of Post.
I want to use MonthPost when filtered date is smaller than month.
_models = Model.extra(
select={'score': 'like_count + comment_count'},
order_by=('-score',)
)
I use extra about above two models. Post works well, but MonthPost doesn't work.
django.db.utils.ProgrammingError: column reference "like_count" is ambiguous
LINE 1: ... ("archive_post"."is_show" = false)) ORDER BY (like_count...
This is the error message.
_models.values_list("post", flat=True)
And then, I want to extract OneToOne field(post) from MonthPost.
I try to use values_list("post", flat=True). It return only id list.
I need to post object list for django rest framework.
I don't' quite understand what you are trying to achieve with your MonthPost model and why it duplicates Post fields. With that being said I think you can get the results you want with this info.
First of all extra is depreciated see the docs on extra. In either case, your select is not valid SQL syntax, your query should look more like this:
annotate(val=RawSQL(
"select col from sometable where othercol =%s",
(someparam,)))
However, what you are after here requires neither extra or RawSql. These methods should only be used when there is no built in way to achieve the desired results. When using RawSql or extra, you must tailor the SQL for your specific backed. Django has built in methods for such queries:
qs = Post.objects.all().annotate(
score=(Count('like_count') + Count('comment_count'))
A values_list() query needs to explicitly list all fields from related models and extra or annotated fields. For MonthPost it should look like this:
MonthPost.objects.all().values_list('post', 'post__score', 'post__created_time')
Finally, if the purpose of MonthPost is simply to list the posts with he greatest score for a given month, you can eliminate the MonthPost model entirely and query your Post model for this.
import datetime
today = datetime.date.today()
# Filter for posts this month
# Annotate the score
# Order the results by the score field
qs = Post.objects\
.filter(created_time__year=today.year, created_time__month=today.month)\
.annotate(score=(Count('like_count') + Count('comment_count'))\
.order_by('score')
# Slice the top ten posts for the month
qs = qs[:10]
The code above is not tested, but should give you a better handle on how to perform these types of queries.

Related Links

Dynamically import a callable given the full module path?
python chaining
py2app and xml.etree.ElementTree
What is the difference between isinstance('aaa', basestring) and isinstance('aaa', str)?
Is this essential functional programming feature missing from python?
Hooking into a wave-out on different platforms
What causes subprocess.call to output blank file when attempting db export with mysqldump?
How do I remove something form a list, plus string matching?
Reference to Part of List - Python
Django Delete all but last five of queryset
How do I limit the number of active threads in python?
Calculating the pixel size of a string with Python
Python nested lists and recursion problem
Problems PUTting binary data to Django
How to use long integers in Python to build a range?
Should I use Lex or a home-brewed solution to parse a formula?

Categories

HOME
caching
semantic-ui
shopify
nlp
ubuntu-16.04
codeeffects
flyway
snap.svg
java-home
diagram
lotus-notes
ndis
dryioc
cpanel
multiple-monitors
sendkeys
jni
statusbar
data-cleansing
geopandas
nesc
partial-application
multichoiceitems
piecewise
ipfw
shapes
rhel.net
polyfills
lexical-analysis
mediawiki-extensions
xbim
rkt
context-free-language
rdw
broadcast
goquery
iphone-developer-program
rxvt
nsfetchedresultscontrolle
sql-import-wizard
manifest.mf
git-annex
windows-nt
ng2-material
mongoskin
clob
django-south
spinlock
supportmapfragment
sun-codemodel
bluesnap
license-key
servlet-3.0
difference
coldfusion-7
js-cookie
windowlistener
harp
robocode
ticket-system
pgagent
proximity
rhel5
vcl
author
alpha-transparency
pic24
arangodb-php
facebook-chat
loop-invariant
nsmatrix
trimming
iconv
vt100
returnurl
web-safe-fonts
getusermedia
icefaces-3
nemerle
serp
phpcrawl
chatroom
winverifytrust
code-design
visual-studio-2010-beta-2
internals

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App