The best way to act with a model in Django [closed]
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this questionI have a Task model:
class Task(models.Model):
text = models.TextField()
datetime = models.DateTimeField(auto_now_add=True)
taken = models.BooleanField(default=False)
done = models.BooleanField(default=False)
client = models.ForeignKey('UserProfile', related_name='tasks_given')
executor = models.ForeignKey('UserProfile', related_name='tasks_received')
def __unic开发者_开发知识库ode__(self):
return 'Task #'+str(self.id)
and I have to handle its creation, validation, cancelling etc.
What's the best way to do it? Is it better to have one (for all cases) or few (for each case) functions in views.py
? Is it better to have one template with a lot of {% if %}
or is it better to have a few? Any other hints will be appreciated =)
For actions, you'd better extend class-based generic views, they are quite modular, have most of the functionality already baked in and sensible defaults for template names etc.
https://docs.djangoproject.com/en/1.3/ref/class-based-views/#detail-views
They are based on mixin composition, so for each piece or step of functionality there is a very specific method you have to override. Once you get it it is very simple.
For templates, use the extends
and include
tags and avoid repeated code. Try to use most automatically generated code as you can.
You can use the django-admin site, as illustrated in chapter 2 of the tutorial.
I'm not exactly sure what you mean by "best way to act," but if you want to handle the object creation and validation, you can write extra methods in your model.
class Task(Models.model):
...
## fields
...
## Example of a method on the model
def validate(self):
## validate the model here
I think you want to minimize the validation code in the view. It would be nice if from your view, you can validate like:
new_task.validate()
instead of having to write the validation in every view you want to use the Task model.
精彩评论