Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8010219
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T18:40:17+00:00 2026-06-04T18:40:17+00:00

I’m trying to refactor my little voting functions. I’ve got two of them which

  • 0

I’m trying to refactor my little voting functions. I’ve got two of them which do almost exactly the same thing, only to different model fields. Voters can add stars to a song if they like it, and they can add flags to a song if they dislike it. The voters are then associated with the song via a many2many relationship, so it can be determined if they already voted on that song. If so, a star (or a flag) is removed from the song and the relationship between voter and song is removed also.

Here is the function that adds or removes stars:

# models.py
class UserProfile(models.Model):
    user = models.ForeignKey(User, unique = True, related_name = 'profile')
    liked_songs = models.ManyToManyField('Song', blank = True, null = True)
    disliked_songs = models.ManyToManyField('Song', blank = True, null = True)

class Song(models.Model):
    song_id = models.CharField(max_length = 36, primary_key = True)
    last_accessed = models.DateTimeField()
    stars = models.IntegerField(max_length = 5, default = 0)
    flags = models.IntegerField(max_length = 5, default = 0)

# views.py
def vote(request, song_id, task):  # 'task' should be either 'stars' or 'flags'
    song = Song.objects.get(song_id = song_id)
    voter = request.user.get_profile()

    # Voter does not already like the song
    if not voter.liked_songs.filter(song_id = song.song_id):  # (*)
        try:
            # Increase vote, set 'last_accessed', add Song to UserProfile.liked_songs
            Song.objects.filter(song_id = song_id).update(
                stars = F('stars') + 1,  # (*)
                last_accessed = datetime.datetime.now()
            )
            voter.liked_songs.add(song)  # (*)
        except:
            raise
    else:
        try:
            # Decrease vote, set 'last_accessed', remove Song from UserProfile.liked_songs
            Song.objects.filter(song_id = song_id).update(
                stars = F('stars') - 1,  # (*)
                last_accessed = datetime.datetime.now()
            )
            voter.liked_songs.remove(song)  # (*)
        except:
            raise
    return "Done."

The function that adds or removes flags is exactly the same, except for the marked (*) lines:

if not voter.disliked_songs.filter(song_id = song.song_id)
flags = F('flags') + 1,
flags = F('flags') - 1,
voter.disliked_songs.add(song)
voter.disliked_songs.remove(song)

Now here’s my first question: What do I have to do to use only one function for liking and disliking a song? I have already introduced the argument task but I can’t seem to write task = F('task') + 1,, because there is no field name ‘task’ in the Song model.

Bonus question: The only difference between stars = F('stars') + 1, and stars = F('stars') - 1, is the operator (+ or -). Is there a way to have an operator in a variable, i.e. task = F('task') myoperator 1,?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T18:40:18+00:00Added an answer on June 4, 2026 at 6:40 pm

    Answer for Bonus question: Why dont you have a function that accepts the operator as argument and evaluates the expression based on argument?, like the following example:

    >>> def f(op):
    ...  return (eval("3"+op+"2"))
    >>> f("+")
    5
    >>> f("-")
    1
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
I'm trying to select an H1 element which is the second-child in its group
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I am trying to render a haml file in a javascript response like so:
I want use html5's new tag to play a wav file (currently only supported
I would like to run a str_replace or preg_replace which looks for certain words

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.