I am implementing a social network project on Django. 2 of my models, have the following fields.
class Profile(models.Model):
user = models.OneToOneField(User...
followers = models.ManyToManyField(Profile...
class Post(models.Model):
owner = models.ForeignKey(Profile...
content = models.CharField(...
likes = models.ManyToManyField(Profile...
Now I created add_likes, add_followers, and edit_post views and they are very similar to each other. Here is a rundown of what they do:
add_likes
- Receive a JSON object with a "target_post_id" and a boolean "like_status" (for Like or Unlike)
- Check validity JSON object and convert it to python objects
- Check if target_post exits
- Check is user profile does not own the post
- Add or Remove user profile to Post.likes based on like_status
- Return JsonResponses based on result (success or reason for failure)
add_followers
- Receive a JSON object with a "target_profile_id" and a boolean "follow_status" (for Follow or Unfollow)
- Check validity JSON object and convert it to python objects
- Check if target_Profile exits
- Check if target is not own user profile
- Add or Remove user profile to Profile.followers based on follow_status
- Return JsonResponses based on result (success or reason for failure)
edit_post
- Receive a JSON object with "target_post_id" and "new_content"
- Check validity JSON object and convert it to python objects
- Check if target_post exits
- Check is user profile owns the post
- Change Post.content based on new_content
- Return JsonResponses based on result (success or reason for failure)
Is there a way to avoid creating 3 views that are very similar to each other?
I have a few solutions I thought of:
Use a base followable model that has an owner (one is to one with user) and follower (many to many with user) field. Both Profile and Post will inherit from this (In the case of Post, the likes are the followers). The model will also have its own method for updating its contents (steps 3 to 5). The problem however is if in the future I wanted to change how likes work (for example adding a dislike). I am also skeptical if this will raise issues in my queries (querying for what my User is currently following will give both Posts and Profiles)
Use a function that will perform steps 2 to 5. My problem with this is it will have a lot of if-then statements or switch-cases depending on the content of the JSON-object.