« first day (3797 days earlier)      last day (1134 days later) » 

12:10 AM
hey this is weird.
I changed some info on a user then queried the user from the same function just to test it that all changes were saved and yes it was saved.

then i tried to call that details out form another function and looks like it has changed back to "null"
user_obj = user.query.filter_by(id=user_id).first()
        user_object.test = request.sid
        db.session.commit()
        x = users.query.filter_by(id=user_id).first()
        print(f'x.id: {x.id} , x.sid: {x.test}')
everything works fine here and I can see the x.test value correct

but then if i check the database ( pgadmin 4 ) i see it null and when i try to call user.test anywhere else it says " None
 
12:46 AM
is it imposible to save sessions ?
 
1:02 AM
it's user_object not user_obj*
user_id =1
z = users.query.filter_by(id=user_id).first()
z.test = request.sid
db.session.commit()
x = users.query.filter_by(id=user_id).first()
print(f'x.id: {x.id} , x.test: {x.test}')
just cleaned the code
i think iam not updateing the database correctly, but every title i've seen over the internet on this subject says that i've updated the database correctly.
 
 
7 hours later…
user13727121
8:04 AM
My program here is executing infinitely, the else part particularly, break won't work because I want it to execute it again until the program has received a username from the user. Code to this issue: dpaste.com/BWB2D89VY
 
it must be name != "\n" I guess
 
user13727121
@python_user no, that's if it's not an empty string, in other words, the user has given a username.
 
yeah, sorry
did you try moving the input inside the loop?
 
Yeah, after you tell the user that a username is required, you should probably also let them input one
 
user13727121
@python_user :fp: well that fixed it, thank you
 
user13727121
8:18 AM
@Aran-Fey i also noticed that it works if i call the function again in the else statement without putting the input inside the while loop, but that's not efficient I see
 
@Aran-Fey Oh my, that is impractical. PEP 585 even explicitly noted these to be available.
Note that the __parameters__ is available on specialized types, but empty. E.g. list[int].__parameters__
 
That's expected, since a list[int] accepts no more arguments. It'll be non-empty on a list[T]. As far as I can tell, GenericAliases and classes that inherit from typing.Generic still have __parameters__ like they used to. But hardly anything in the stdlib actually does inherit from Generic
 
user13727121
@Aran-Fey in the if statement, is it better to use break or return? because they both worked without any error
 
Assuming you don't need a return name, either one is fine
I like break very marginally better because sometimes you will want to run some more code after the loop. If you ever add some code after the loop, you won't need to rewrite your return to a break
 
user13727121
@Aran-Fey nope, it's just a greeting message. I forgot that return won't execute any more code after it, had to test it out, so yeah, I do agree that break is a bit better if I have more code after a loop, thank you.
 
8:31 AM
@Aran-Fey After experimenting with GenericAlias a tad, I'm decently sure your only option is manually define the parameters of the PEP 585 types.
In case you don't need the variance, then typing.XXX._nparams will tell you the arity. -1 is variadic.
 
@Aran-Fey Most classes in collections.abc simply do __class_getitem__ = classmethod(GenericAlias), and typing is a tiny bit better, using _SpecialGenericAlias for the sole purpose of limiting how many type arguments a generic accepts. Still no TypeVars in sight though, just a number of how many arguments are valid. Idk how this awful implementation passed
 
As far as I can tell, a lot of changes lately are only aimed at the specific use-case they are meant to solve, not general usability.
Kinda shuddered at except *: ...
 
@MisterMiyagi I'm thinking of doing that, but at this rate... there might not be anything left for me to work with in python 3.10 :|
 
I assume libs such as pydantic don't need the stuff?
 
Oho, I didn't know about pydantic. If it really enforces types at runtime, then it definitely needs this stuff
 
8:43 AM
i hate how zip(*[iter(s)]*n)
 
8:58 AM
First contact with pydantic: Disappointing
class Test(pydantic.BaseModel):
    foos: collections.abc.Iterable[int]

print(Test(foos=[1, 2]))
# foos=<list_iterator object at 0x7f5c6a6b59d0>
 
so they call iter on iterables? oO
 
More disappointment: TypeError: Fields of type "<class 'collections.abc.Container'>" are not supported.
I guess they're not really caught up with 3.9 yet? Can't blame them, I suppose
 
Urgh. Reading through their tracker has some unpleasant issues with 3.9.
 
9:30 AM
Been a while since the last one, so here's a riddle even though it's not all that interesting: Guess the output. I'm curious where/how that's implemented
Almost 1 and a half years since the last riddle, wow
...and I still don't have editing privileges on sopython
 
Always have to recheck the docs on __init_subclass__... D:
__new__ is the only one I remember consistently.
 
Man adapting existing multithreaded code is hard :P I forgot to release a lock when the queue was empty and wondered why the socket never got closed :D
 
9:46 AM
Sounds like manually implemented synchronisation. My condolences.
 
9:57 AM
I mean someone somewhere has to do it manually :P It's C code, so I think the code is fine, I just forgot the lock, it's been a long time since I did anything with locks
 
@Hakaishin you don't have doors? :p
 
how do we do spoilers in chat?
 
there's an sopython spoiler obfuscator. I'm using a userscript for that, AFAIK from view spoiler
 
either that obfuscator is broken, or it requires some link that has been blocked for me
i can open it but clicking encode doesnt do anything
 
in Advent of Code, Nov 30 '20 at 8:06, by wim
Kevin's userscript for adding a spoiler button in chat UI
 
10:10 AM
thanks Miyagi!
and Kevin
@Aran-Fey i missed these, got 1 of 6 right
 
10:30 AM
@Aran-Fey There was a recent kerfuffle about ORM support in pydantic, where the principal developer appeared to be suggesting people should just write SQL instead ...
 
hey - bet that was a fun kerfuffle :)
 
ho :)
@JonClements Not really, just people with nothing better to think about getting hot under the collar about ones and zeros. At the moment I'm struggling to regularise compensation for an international team of twenty+ developers, so it all seems pretty trivial and remote to me.
 
ones and zeros are fun though, right? :p
 
10:54 AM
As long as we don't take them too seriously.
 
11:12 AM
for i in range(len(arr)):
        ans.append(i*arr[i]-prefix_array[i] + suffix_array[n-i]-(n-i)*arr[i])
im trying to calculate the sums of the absolute value of differences between an element and every other in the array. does this look correct?
 
@Trajan no
unless by "array" you mean "list"
 
ok
 
I don't see anything in there translating to the "differences between an element and every other" so I am hardpressed for "no" as well.
 
thanks guys
 
11:39 AM
if you have a pair of indices [x,y] and you want to check if they in are a set, how can you do this in python? list isnt a hashable type?
 
@Trajan nope, it isn't. Tuples are.
 
You could convert to tuples, rendering the values hashable and immutable.
You may well find you could use tuples in most places in your code ...
 
still doesnt work in python 3
visited = set((startRow,startCol))
visited.add((next_step[0],next_step[1]))
 
@Arne I've known what a transistor is since 1964. How long do I have to wait for the rest of the instructions?
@Trajan "Doesn't work" is about as unhelpful as a problem description can be.
 
@holdenweb it's not like they've been asking for help here for 3.5 years
 
11:48 AM
sorry i had a typo, you are correct thanks
 
@holdenweb damn, the gamble's up. it was just a deflection to talk about something interesting, I never knew how to install drivers in the first place
 
>>> visited = set()
>>> visited.add(("a", "tuple"))
>>> visited
{('a', 'tuple')}
>>>
@Trajan Quite.
 
thanks
 
@Arne My retribution is certain though slow. No claim escapes Foul 'Ole Ron's scrutiny, bugrit.
 
if you have an array and for each element you want to calculate the absolutes differences of all indices in the array which have the same value, can you do this better than O(n^2)?
 
11:52 AM
@Trajan STOP
 
ok
 
Do you have arrays or do you have lists?
 
hi , does anyone knows how to send private message using socket IO ?
 
i have a list
 
@Trajan then please call it a list. There are at least three kinds of arrays in python, and lists are neither of those. And since you have numerical problems it matters what objects you have.
 
11:54 AM
yeah its a list thanks
[2,3,2,2,3,4] for element at index 2 this would be |0-2|+|3-2| = 3
 
Think about it whether it helps if you take an index -> list of other indices with the same value mapping
 
@AndrasDeak three?
 
@MisterMiyagi at least
 
so hashmap first ok
 
@AndrasDeak I'm only aware of array.array and numpy.array. Are there some new kids on the block, or am I just getting old?
@Trajan since this example implies most values are duplicate: does your actual data have mostly duplicates?
 
11:58 AM
yes
like in the example i gave
 
I observe that repeated runs of a given value make no difference to the sum, assuming the value of the element at index 4 would be 4. Your example is a little vague with only one data point.
 
@MisterMiyagi bytearray
(and of course more esoteric things like xarray)
@holdenweb for index 0 (also with value 2) you'd have 2 + 3 == 5. Or did you mean something else?
 
I just realised that my interpretation of "absolutes differences of all indices in the array which have the same value" does not match the example.
 
all other indices is probably key
I think it might not be much better than O(N^2)
of course the coefficient might be a lot smaller
 
i think O(nlogn) is fast as you could do this
 
12:08 PM
Knowing Trajan this is just another coding challenge where they got a timeout with the first naive implementation
 
Runs counter to the example, which appears to only consider index values below the one under consideration.
 
@holdenweb no, for index 2 it considers index 0 and index 3
 
@Trajan This message appears to contradict that assertion. What did I misunderstand?
 
there are 3 2's i considered the middle one
there is one 2 higher |3-2| = 1
and one lower |2-0| = 2
 
OK, I give up. Maybe I'm just being obtuse, but if I can't extract sufficient information to offer an answer to your question I'll regard myself as part of the problem and place myself hors de combat.
 
12:13 PM
first 2: |2-0|+ |3-0| = 5
second 2: |2-0|+|3-2|
third 2: |3-2|+|3-0| = 4
for [2,3,2,2,3,4]
 
for i0, val0 in enumerate(lst):
    tot = 0
    for i, val in enumerate(lst):
        if val == val0:
            tot += abs(i - i0)
    # do something with tot
trying to change that ^
 
Someone already pointed it out in comment, but...
The current answer is (you see what's wrong.) Although they're both O(1) apparently. (I guess)
 
ugh. Let me find a duplicate
 
I can't.
I tried.
Actually that's the only one I found when encounter a recent transpose question (see linked questions) -- although the new one is a little different with list of np.array. (weird)
 
@AndrasDeak i cant work this out either
 
12:18 PM
closed
 
ive sums in my head everywhere
 
@Trajan work what out? I was just showing the naive implementation to holdenweb to demonstrate what you're trying to do
 
yeah but speeding that up is what im struggling with haha
 
@AndrasDeak they key is that the description is vague enough for me to go enjoy the sun. ;)
 
@MisterMiyagi oh no argument there. You can go for a hike and return to another random coding challenge question :P
 
12:25 PM
@AndrasDeak warms the heart to know there is a place that always welcomes you with random nonsense. :)
 
12:51 PM
@ParitoshSingh I also got those 2 wrong even after I'd already seen the output once :|
 
@MisterMiyagi also re arrays, pandas.pydata.org/docs/reference/api/pandas.array.html pandas array too :D
 
Level 2:
class Foo:
    __new__ = None

Foo.__init_subclass__ = lambda cls: None

print(type(Foo.__new__))
print(type(Foo.__init_subclass__))

print(type(vars(Foo)['__new__']))
print(type(vars(Foo)['__init_subclass__']))
 
@ParitoshSingh it doesn't say why to have that type when one has Series...
 
i believe the issue was with the Nullable int dtypes that were introduced
since numpy doesnt directly play along with them at all
As for why they felt the need to introduce array to answer that problem though, i cannot say.
 
1:08 PM
 
ah that's perfect, thanks
 
2:00 PM
typing.NoReturn
    New in version 3.5.4.
    New in version 3.6.2.
Go home python docs, you're drunk
 
doesn't that usually mean backported and added in a patch version?
 
I have no idea, but even if that's true, isn't the 2nd line redundant?
 
no, because 3.5.3 and 3.6.1 apparently didn't have it
 
Ah, that would make sense I guess
 
so added in 3.6.2 and backported to 3.5 in patch 4
I've seen it in other places before, can't recall. one example might be the removal of u as an illegal string prefix in 3.0-3.3 - several early versions consider it illegal
 
2:11 PM
it's usually for things removed to fix bugs.
the typing versioning is kind of a hint that maybe including it in the stdlib wasn't the best idea.
 
@MisterMiyagi I need your help with a design decision: Given a function get_type_parameters such that get_type_parameters(typing.List) == (T,) and get_type_parameters(typing.Callable) == (A_contra, R_co), what would you expect as the return value of get_type_parameters(typing.Literal)? None? ()? (object,)? An error?
 
What's the return for Tuple?
 
(T_co,). Can be combined with is_variadic_generic(Tuple) == True to figure out that you can pass an arbitrary number of them
 
drinks T
I'd say T and variadic is correct.
 
I've chosen to define "generic" as "anything that can be subscripted", but it's proving a little problematic
 
2:15 PM
Considering how literals are... Literal types.
 
Hmm. Thinking of literals as a type is... something I hadn't considered
I need to run, but I'll ponder it, thanks
 
No haste, I'll be stuck for a while trying to grok what it means to define Literal via Literal.
 
As a layman I find "literal type" really weird.
 
Just think of them as degenerate dependent types. ¯\_(ツ)_/¯
 
I think of them as one of few things for which the type is guaranteed
weird that 42 and 'potato' are somehow the same type
even if that type is just a superset of concrete types
 
2:24 PM
That's not the point for being a smartass, is it?
 
homeomorphic endofunctors or bust
 
don't tempt me :P
 
2:41 PM
Hello, everyone! This is my first message in stackoverflow chat. What do you discuss usually here?
 
Hi! all things python, whatever comes in and sounds interesting
 
3:23 PM
What does dict(default=telemetry) mean? Does that mean it's an anonymous key?
 
it just means there's a key "default" mapping to the value telemetry
 
why use that syntax instead of {"default": telemetry}?
 
for the same reason people use a.update({"key": value}) instead of a["key"] = value
 
which is?
 
the great Cargo will smite you if you do not!
 
3:28 PM
xD
 
@Hakaishin I find it to be less typing of quote marks. Especially for config-like things I often use the dict call
 
now I feel guilty for implying that The Great Cargo made you do that...
 
The henchmen are already on their way
 
ah I see :P
Holy moly I just learned about the synchronized keyword and it is soooo freaking amazing. I can't believe how powerful it is and all the things it does in the background
 
3:54 PM
@AndrasDeak Tell them to hurry. I have a paper review to finish today, and I'm all out of red ink. chews bubblegum
 
Also did you also have it that running python setup.py install doesn't always pick up new changes? It just happened to me and the only thing that solved it was deleting the package under site-packages
talking in the pyscaffold context, not sure if that is important
 
IIRC setup.py install does not replace an existing installation if the version is the same.
Been a while since I used that, though...
 
In my usage experience it updates 99% of the time
 
@Hakaishin do you need compilation so setup.py develop won't cut it?
 
@AndrasDeak I'm not sure, sometimes yes sometimes no. In my own projects I use develop successfully, but in this larger project I try develop first but often have to still resort to install
 
4:05 PM
isn't running setup.py with python depcrecated? I have seen a few projects only supporting pip install -e . by now
 
Beyond the deprecation (and pyproject.toml compatibility) is there a difference in behaviour?
 
I wanna say yes, but I can't tell you what
the accepted answer is bad, but some info is sewn around this post: https://stackoverflow.com/questions/30306099/pip-install-editable-vs-python-setup-py-develop
On the first glance, nothing that sounds like it could be Hakashin's issue though
 
Can you source this? I searched a bit but couldn't find anything only that setup.py test ist depr, but not install or setup.py in general
 
[{'name': 'UEFA Champions League', 'country': '', 'year': 2011, 'winner': 'Chelsea', 'runnerup': 'Bayern Munich'}]
that is my results['data']
how do i access the winner?
results['data']['winner'] doesnt work
 
@Trajan seriously?
@Trajan check type(results['data'])
 
4:16 PM
ill try that now tanks
 
@Trajan and now you know why an endless stream of code challenges is a waste of time
 
4:38 PM
Looking at some code I wrote last year. It's not so much spaghetti code, more like meatloaf
 
@inspectorG4dget need one more
 
I extract some raw data from two dozen files and multiple directories, combine them together, do some useful work on them, then dump the result to an output file. But now I need to know which segment of output came from which file and directory -- information that was lost when I minced everything up and smooshed it into a loaf
 
And I would do anything for maintainability...
 
I know what to do -- redesign everything surrounding do_useful_work so I can retain the metadata -- but that's basically 95% of the program
Conclusion: It's a pain and I don't want to ∠( ᐛ 」∠)_
Briefly considered appending the metadata to the string, like "(c:/foo/bar.txt)hello world" and feeding it through do_useful_work. Then I could extract it from the output file without having to redesign the program structure. But it's rather like designing a file cabinet that can survive a trip through a meat grinder intact.
 
5:04 PM
Custom class that holds metadata? :P
 
🤔🤔🤔
 
Custom metaclass that holds data? :P
 
metadata class that customizes holds?
 
There's a point in life when you just have to eat the spaghetti.
 
only the pieces that didn't stick to the wall
 
5:08 PM
Hard pill to swallow. Ironic since spaghetti is usually quite easy to swallow.
 
anyone here use tableau?
more specific question: if I have a tableau online license and I create a dashboard with that, is there a way for me to share a link with someone that doesn't have a tableau license to view my dashboard?
 
Their website advertises tableau online as "Publish dashboards and share your discoveries with anyone" so I get the impression it's possible
unless "anyone" means "any of our customers"
 
that's what I'm trying to wrap my head around. Doesn't seem particularly explicit if you don't have a license to experiment with
 
If there isn't a big friendly button in the UI that says "copy public url to clipboard" then my optimism is fading
I can't find any documentation without registering an account on their website, which is a firm sign that they want to draw people into their walled garden whether they want to or not
 
5:31 PM
that's really unfortunate. Thanks for the confirmation :)
 
On the other hand, it's in their best interest to provide an unobtrusive experience for their customer's customers, so at the very least I'd expect no-account sharing to be possible for super gold deluxe tier members
 
6:04 PM
@MisterMiyagi It was when typing entered the stdlib I knew it would eventually take over the language. I regards it as a personal itch of Guido's, which I would rather have seen inflicted on some other language, that I need not then use.
 
cbg
@AliTlekbai I'm late to the party. Sometimes this channel is just memes.
 
As long as each meme carries a kernel of programming wisdom
 
hello, does anyone knows how to make a regular integer column to autoincrement with a start up value ?

i think the syntex was something like that. but I cant remember the rest of it.

`db.Column(db.Integer,autoincrement=true)`
i cant remember how we used to call the startupvalue , defaultvalue ?
 
@LoopingDev What do you mean by a "integer column"? What 3rd party library are you using here? This isn't in the standard Python library.
 
oh sorry , i forgot to mention Flask-SQLALchemy
 
6:18 PM
rather than trying to remember the exact syntax, I suggest googling for the docs and read those.
 
i did :D , the documents doesn't include everything and it's kinda hard to find
 
I have never used flask-sqlalchemy, but for similar libs, I have to constantly refer to to the docs.
 
@LoopingDev without any information on what library/framework you're using, all I can say is "check the documentation"?
 
@inspectorG4dget flask-sqlAlchemy
@Code-Apprentice yeah I did that as well but they didn't cover everything because to them it's obvious or easy to find, well not everyone
 
db.Column(db.Integer, primary_key=True)
 
6:20 PM
so you want the syntax for the default value?
 
Unless you are using some DB like Redshift, which complains about auto-incrementing the primary_key by default
Or any columnar DB I suppose, which I think is unlikely
 
@roganjosh i think that is for the primary_key , we use of ID , but autoincrement=true is what we use for things like serial No.
 
I should ask what do you mean by "startupvalue, defaultvalue"?
 
@Code-Apprentice thanks , that is for SQlalchemy not flask-sqlALchemy but They are pretty close
 
oh right...I just clicked on the thing that came up with my google search. Forgot to double check which lib it was.
 
6:23 PM
@Code-Apprentice well, i wanted to create serialNo for invoices, so I just wanted to start the first invoice with 1000 and add 1 every new row
 
@holdenweb I’m somewhat divided on typing. It’s very useful for developing libraries, and unobtrusive for other people. So, practicality and purity and all that. But I cannot help feel that while it quacks and waddles alright, it seems to have hoofs and know barely more than one trick.
 
Ah, the one-trick-pony-duck
 
@LoopingDev Maybe this will help? stackoverflow.com/questions/10494033/…
that is still sqlalchemy, not flask-sqlalchemy, but hopefully it gets you in the right direction.
The second answer looks the most idiomatic
 
i guess , thanks a lot

it's not for flask-sqlalchemy but they are both have similar sytax
` Column(INTEGER(unsigned=True, zerofill=True),
Sequence('article_aid_seq', start=1001, increment=1),
primary_key=True)`
 
7:13 PM
I really wish there were more functions in the stdlib that simply returned False instead of throwing an exception... wrapping every use of issubclass and x in some_dict in a big, fat try ... except is driving me nuts
 
7:37 PM
@Aran-Fey I see why you'd want that, but it seems to me that at least issubclass returning False would be "technically correct, the best kind of correct", yet useless
 
Oh, I'm not saying these things should behave differently than they do now, I'm saying I wish there were alternatives. Say issubclass(nothrow=True) or dict.contains(x)
 
hmm, yeah
 
I have a checker board as a class Board:
 
Air
Isn't performance a priority for built ins
 
import pygame

pygame.init()

wn = pygame.display.set_mode((600, 600))

class Board:
    ...

board = Board(200, 200, 50, 50, 5, 5)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    wn.fill((0, 0, 0))
    board.draw()
    pygame.display.update()
pygame.quit()
It mainly displays a checkerboard in the pygame window.
I'm wondering, is it a better practice to define each cell as a `Rect` and store them into a list, or is it better to not use the memory, but perform a calculation to each cell's position every time the `draw()` function is called?
Here is the method to define each cell as a Rect beforehand:
And here is calculating each cell's position every time the draw function gets called: pastebin.com/SLPKqSgw
 
7:48 PM
That's a lot of code, can you upload that somewhere else?
 
ok
thanks for any help
 
I don't use pygame, so I could be completely wrong, but I doubt there's a significant difference between the two
 
@AnnZen you seem to have two working versions, yes? Just compare them.
 
@AnnZen memory is usually a lot cheaper in python than processing. unless you are out of memory, I'd go for storing the cells instead of recomputing them.
 
@MisterMiyagi oh
@AndrasDeak but i can't compare which is a better practice
@MisterMiyagi thanks, i'll go with that. i just didn't think that storing 64 class objects in a list just to display a board sounded very efficient.
 
8:04 PM
@AnnZen fair enough
 
8:56 PM
a question about question deletion by 10k+ users: what was the point of deleting this question? (I don't care about the 25 rep loss) but ...why? and two of the deleters seem to be promoting their own free & paid regex courses. that feels dodgy. (and the linked dupe is too specific, my answer was generalised.) stackoverflow.com/q/66480523
 
@aneroid There's a recent metadiscussion on deletions in the regex tag, in case you want to join the fun. Bring popcorn and body armor.
 
9:12 PM
hahah, happy to watch/read
@MisterMiyagi is this this one? meta.stackoverflow.com/questions/405460/…
 
@aneroid yeah
Is there some good dupe for ":= is a syntax error on Py3.7"?
 
I see the question you're referring to. I think we need that to exist with that one answer "The walrus operator is a new addition in Python 3.8..." worth closing to avoid new answers - but don't know what reason
 
@aneroid Top answer by Wiktor Stribizew, the guy who keeps closing questions as dupe of this regex reference. What a farce :|
 
9:27 PM
@Aran-Fey yup, an absolute farce. if SO didn't have strong guidelines on politeness, I'd call out the bs in his answer - also, in such issues, rep matters; so I'm unlikely to be heard
if one could understand regex rules, they wouldn't be asking what a specific regex means. pointing to the manual is not an answer. (yeah, we can hope that they first RTFM'ed but that doesn't always help actually know/understand the content.)
for the simple ones, sure, close and link. but how often?
and regex's are considered a mini-language with it's own syntax. so by that guy's standard, we should close most Python questions with "read the language spec"? uugh
 
9:56 PM
Django question: How come I can do (Foo being a model defined in models.py) Foo.objects.values() but I can't do (foo being an object like: foo = Foo()) foo.values
How can I get the same result I do from values when I apply it on objects. but only for a single instance of model Foo not on a QuerySet?
 
10:07 PM
Why would you even want to do that? Why use a Foo instance to query the database for other Foo instances?
 
I might be unreasonable, I am new to django. All I really want is, to get a dict object from my model instance
as far as I understand this is achievable on a QuerySet by using the .values() function
but I couldn't find how to do so on a single object
 
aha, so it's an XY problem
this should solve your problem, I think?
 
yeah I saw the hack mentioned in the answer in the code I am reading: SomeModel.objects.filter(id=instance.id).values()[0]
I thought it's a bad practice, or a hack
but seeing it is mentioned in the answer
I guess I will stick with that
Well thanks for the link :)
 
10:35 PM
@Silidrone Alternatively model_to_dict(SomeMode.objects.get(pk=pk).
Or if you already have the instance: model_to_dict(instance).
no reason to do an extra DB query if you already have a model instance.
@Silidrone To answer your original question, you can do Foo.objects.values() but not foo.values() because Foo.objects is an instance of a class that has a values() method, but foo is not. To convert a single model object to a dict, do model_to_dict(foo).
 
@Aran-Fey only half a farce... there's also another repyam who's been trying to make a scene on meta. They share a feud. This post is only one facet of that I think.
 

« first day (3797 days earlier)      last day (1134 days later) »