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

Update models.py #369

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 33 additions & 9 deletions django_tests/models.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,51 @@
from six import python_2_unicode_compatible

from cloudinary.models import CloudinaryField
from django.db import models


@python_2_unicode_compatible
class Poll(models.Model):
id = models.AutoField(primary_key=True)
"""
Represents a poll with a question and an optional image.
"""
question = models.CharField(max_length=200)
image = CloudinaryField('image', null=True, width_field='image_width', height_field='image_height')
image_width = models.PositiveIntegerField(null=True)
image_height = models.PositiveIntegerField(null=True)
image = CloudinaryField('image', null=True, width_field='image_width', height_field='image_height')
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)

def __str__(self):
return self.question

def save(self, *args, **kwargs):
"""
Custom save method to update modified_at timestamp.
"""
self.modified_at = timezone.now()
super(Poll, self).save(*args, **kwargs)

@python_2_unicode_compatible
class Choice(models.Model):
id = models.AutoField(primary_key=True)
poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
"""
Represents a choice in a poll and the number of votes it has received.
"""
poll = models.ForeignKey(Poll, on_delete=models.CASCADE, related_name='choices')
choice_text = models.CharField(max_length=200)
votes = models.PositiveIntegerField(default=0)

def __str__(self):
return self.choice.encode()
return self.choice_text

def vote(self):
"""
Increment the vote count for this choice.
"""
self.votes += 1
self.save()

def save(self, *args, **kwargs):
"""
Custom save method to update poll's modified_at timestamp.
"""
self.poll.save() # Update the parent poll's modified_at timestamp
super(Choice, self).save(*args, **kwargs)