Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

F Expression directly on object causing weird behaviour #549

Closed
dstlny opened this issue Nov 11, 2020 · 1 comment · Fixed by #550
Closed

F Expression directly on object causing weird behaviour #549

dstlny opened this issue Nov 11, 2020 · 1 comment · Fixed by #550
Labels
enhancement New feature or request

Comments

@dstlny
Copy link

dstlny commented Nov 11, 2020

Describe the bug
Serialising a model-object after using a F Expression directly against a objects fields (as opposed to using .filter.update), causes the fields that the F expression is against, to return an object and not the actual value of the field.

Reproduce

Lets say we have the following model:

class Post(models.Model):
	'''
		Represents a post
	'''

	id = fields.IntField(pk=True)
	title = fields.TextField(max_length=150)
	content = fields.TextField(max_length=1200)
	created = fields.DatetimeField(auto_now=True)
	likes = fields.BigIntField(
		default=0
	)
	dislikes = fields.BigIntField(
		default=0
	)

	def __str__(self) -> str:
		return f"{self.created} | {self.title}"

And we try do some 'updates' to a 'post' object like below, causes undefined behaviour.

post = await Post.get(id=post_id)

update_fields = []

if action_type == TypeEnum.LIKE:
	post.likes = F("likes") + 1
	update_fields.append("likes")
	if post.dislikes < 0:
		post.dislikes = F("dislikes") + 1
		update_fields.append("dislikes")
else:
	post.dislikes = F("dislikes") - 1
	update_fields.append("dislikes")
	if post.likes > 0:
		post.likes = F("likes") - 1
		update_fields.append("likes")
	
await post.save(update_fields=update_fields)

Serialising the above post, causes the 'likes' and 'dislikes' field to be replaced by a object, which looks something along the lines of:

{
  "alias": null,
  "operator": "+",
  "left": {
    "alias": null,
    "value": null,
    "name": "likes",
    "table": null
  },
  "right": {
    "alias": null,
    "value": 1
  }
}

Expected behavior
Expecting the value of "likes" and "dislikes" to actually bt eh value of "likes" and "dislikes" on the object after being incremented/decremented, not a object

@long2ice
Copy link
Member

We need a refresh_from_db like Django

@long2ice long2ice added the enhancement New feature or request label Nov 12, 2020
long2ice added a commit that referenced this issue Nov 12, 2020
long2ice added a commit that referenced this issue Nov 12, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants