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

DNS query forwarding if local DNS is resolving
Loading flask configuration using from_object
Python OrderedDict with lambda [duplicate]
TypeError: unorderable types: dict() > dict()
How to install python sipconfig module on win7
Selenium timeout exception even after loop is executed
Converting a unique columns into SFrame headers with corresponding values
ttk progress bar freezing
pandas replace part of a column with another column
speeding up many accesses to pandas dataframe
Performing Arithmetic operations on nested dataframe containing a list
C++ Back-propagation on a Graph; heterogeneous vectors?
How to extract only one capture group using regex for pandas dataframe?
Error with “__str__ returned non-string (type int)”
Pandas: how to change a Series into nested list by index
SciPy ImportError

Categories

HOME
python
dotnetrdf
jdbc
sidekiq
shopify
dynamics-crm
uibutton
smartphone
survival-analysis
couchdb-2.0
rocketmq
hyperledger-fabric
schemacrawler
google-spreadsheet-api
criteria
oclint
jboss-eap-7
xul
cs-cart
symfony2-easyadmin
grub2
jcl
pyephem
zend-framework-mvc
prestodb
ip-camera
aws-cognito
statusbar
rails-activerecord
embedly
header-files
pdfsharp
osmdroid
widevine
image-quality
forum
oracle-xml-db
pljson
modulo
reactivemongo
text-files
nlb
vmd
es-shell
infusionsoft
flex4.5
crop
finite-element-analysis
asmx
dojox.grid.datagrid
dimple.js
android-bitmap
python-hypothesis
nsfetchedresultscontrolle
hspec
backstop.js
rmongodb
multiple-file-upload
jackson-databind
kendo-combobox
squirrel
xmp
spservices
anythingslider
response-headers
twython
on-duplicate-key
rx-groovy
pyopengl
jai
gyroscope-framework
ultrawingrid
mser
surrogate-key
spdy
colt
joox
winrt-httpclient
operations
angulartics
document-database
osx-snow-leopard
apache2.2
appfog
reporting-tools
wpdb
snapjs
attachevent
couchdb-lucene
sunspot-rails
fotoware
entity-framework-ctp5
viewdidload
nemerle
surf
opengl-es-lighting
collect
ihttphandler
for-xml-path
.app
squeel
out-of-browser
recordset
webrat
mvvm-foundation
system-codedom-compiler
project-lifecycle
ajaxpro

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