I'm adding a unicode() method to my model, however when displaying all objects in the interactive it's not working.
import datetime
from django.db import models
from django.utils import timezone
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def _unicode_(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def _unicode_(self):
return self.choice
# Create your models here.
(InteractiveConsole
>>> from polls.models import Poll, Choice
>>> Poll.objects.all()
[<Poll: Poll object>]
They need to be named __unicode__ (two underscores on either side). This is an awkward detail of Python reserved methods that is not immediately obvious by looking at them.
The django docs show you how to specify a unicode method in your model:
https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#other-model-instance-methods
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
Note: These are DOUBLE underscores, where in your example you are only using single underscores.
Its a standard python special class method, as listed here
Related
models
from django.db import models
from django.utils import timezone
import datetime
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.FloatField(default=0)
# ...
def __str__(self):
return self.choice_text
creation
#from polls.models import Choice, Question;from django.utils import timezone
#q = Question(question_text="What's new?", pub_date=timezone.now());q.add(Choice(choice_text='variant', votes=0),Choice(choice_text='Not much', votes=0),Choice(choice_text='Just hacking again', votes=0),Choice(choice_text='The sky', votes=0));q.save;q = Question(question_text="m?", pub_date=timezone.now());q.save
#q = Question(question_text="Third question", pub_date=timezone.now());q.add(Choice(choice_text='single option', votes=0));q.save()
what I am trying to do is filter questions by question_text length being more than amount of choices(children):
#from django.db.models import Count,F, Func,Value
#q=Question.objects.all()
#q.annotate(no=Count('choice')).filter(question_text__regex=r'.{3}')#works
#q.annotate(no=Count('choice')).filter(question_text__regex=r'.{'+str(3)+'}')#works
#q.annotate(no=Count('choice')).filter(question_text__regex=r'.{'+str(F('no'))+'}')
#q.annotate(no=Count('choice')).filter(question_text__regex=r'.{'+str(F('nod'))+'}')
#q.filter(question_text__regex=r'.{'+str(F('choice__count'))+'}')
#q.filter(question_text__regex=r'.{'+str(Count('choice'))+'}')
#Question.objects.filter(question_text__regex = r'.{'+(str(Count('choice')))+'}')
#q.filter(question_text__regex=r'.{'+str(Count([1]))+'}')
#q.filter(question_text__regex=r'.{'+str(Count([1,2,2,2,2,2,2,2,2,2,2,2,2,2]))+'}')
#q.annotate(no=Func(F('question_text'), function='LENGTH')).filter(question_text__regex=r'.{'+str(F("no"))+'}')
#q.annotate(no=Func(F('question_text'), function='LENGTH')).filter(no__gte=F('choice__count'))#works
#q.filter(question_text__regex=r'.{'+str(F("choice__count"))+'}')
#q.filter(question_text__regex=r'.{'+str(("choice__count"))+'}')
#q.filter(question_text__regex=r'.{'+str(Count("choice__count"))+'}')
#q.filter(question_text__regex=r'.{'+str(Count("choice"))+'}')
#q.filter(question_text__regex=r'.{'+str(Value("choice__count"))+'}')
#q.filter(question_text__regex=r'.{'+str(Value("choice__count"))+'}')
question, which has length longer than amount of choices
sorry for this question, but I had a problem with making a dictionary app for a local language, so I wouldn't need English dictionary, my problem is synonyms, I can't figure out how to implement it in my models
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
# Create your models here.
class Voca(models.Model):
name = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("voca:detail", kwargs={"id": self.id, "name": self.name})
class Defination(models.Model):
voca = models.ForeignKey(Voca, related_name='definations')
defination = models.CharField(max_length=500)
example = models.CharField(max_length=500)
etymology = models.CharField(max_length=500)
author = models.ForeignKey(User, default=1)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('created',)
def __str__(self):
return 'Defination given by {} on {}'.format(self.author, self.voca)
class Synonym(models.Model):
words = models.ManyToManyField(Voca, blank=True, related_name='synonyms')
I would like for users to add words, synonyms, antonyms definitions to the database themselves since it is a slang language, so if I can get any help especially for antonyms and synonyms I would really appreciate... thanks
My suggestion would be to remove the Synonym model and add fields to your Defination model.
class Defination(models.Model):
voca = models.ForeignKey(Voca, related_name='definations')
...
synonyms = models.ManyToManyField(Voca, related_name='synonyms')
antonyms = models.ManyToManyField(Voca, related_name='antonyms')
From the Django tutorial:
I've defined my models as follows:
from django.db import models
import datetime
from django.utils import timezone
# Create your models here.
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self): # Python 3: def __str__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self): # Python 3: def __str__(self):
return self.choice_text
Where is choice_set defined and how does this work?
>>> p = Poll.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
>>> p.choice_set.all()
I don't know how deep an explanation you want, but Django defines it for you when you do poll = models.ForeignKey(Poll).
You can read here about it.
choice_set wasn't defined anywhere.
Django creates API accessors for the “other” side of the relationship – the link from the related model to the model that defines the relationship. For example, a Poll object p has access to a list of all related Choice objects via the choice_set attribute: p.choice_set.all().
So choice_set. Where choice is your Choice model in lowercase and _set is kind of Django Manager Tool.
In details, you can read right here .
I'm writing my first django app from
https://docs.djangoproject.com/en/dev/intro/tutorial01/
and i'm experiencing 2 problems.
My Models.py are
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def _unicode_(self):
return self.question self.question
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def _unicode_(self):
return self.question
My First Error is when I do
python manage.py shell
from mysite.myapp.models import Poll,Choice
p = Poll(question="What Your Name",pub_date"1990-02-04")
p.save()
Poll.objects.all()
[<Poll: Poll object>, <Poll: Poll object>]
Why Doesn't it show { Poll: What's up? } instead
[<Poll: Poll object>, <Poll: Poll object>]
My second question is when i type
p = Poll.objects.get(id=1)
p.question.objects.all()
I get this errror
AttributeError: 'unicode' object has no attribute 'objects'
how do i fix it?
you must define your __unicode__ method of your model, not _unicode_.In addition, the code you given return self.question self.question is syntax invalid.
p is a poll instance, p.question is CharField not ForeignKey, has no attribute objects. p has objects, call p.objects.all() works well.
1> its __unicode__ not _unicode_
Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question, self.pub_date
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return self.choice_text
2> objects function is a property of a document instance not a field, p.questions is a document field,
I need to filter database by default every time that I see it (when I save changes or when I open database first time).
Can anybody tell me how to do it?
This is possible with custom custom Managers:
Say you have a class called Book:
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
And you want the admin pages for book objects to only show books by Roald Dahl, then you can add a custom manager:
class DahlBookManager(models.Manager):
def get_query_set(self):
return super(DahlBookManager, self).get_query_set().filter(author='Roald Dahl')
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
objects = models.Manager()
dahl_objects = DahlBookManager()
Then you just need to specify that your ModelAdmin should use the dahl_objects manager, which is explained here.
Here is my models.py:
from django.db import models
class DahlBookManager(models.Manager):
def get_query_set(self):
return super(DahlBookManager, self).get_query_set().filter(processed=False)
class Book(models.Model):
book_name = models.CharField('book',max_length=1000,null=True, blank=True)
url = models.CharField(max_length=1000,null=True, blank=True)
processed = models.BooleanField('Done',)
def __str__(self):
return u'%s' % (self.book_name)
def url1(self):
return '%s' % (self._url, self.url)
site_url1.allow_tags = True
class Admin:
pass
class Meta:
db_table = 'books'
objects = models.Manager()
dahl_objects = DahlBookManager()
here is my admin.py:
from django.contrib import admin
from mybooks.booksdb.models import Book
from django import forms
admin.autodiscover()
class BookAdmin(admin.ModelAdmin):
def queryset(self,request):
qs=self.model.objects.get_query_set()
ordering = self.ordering or ()
if ordering:
qs=qs.order_by(*ordering)
return qs
....
No filter by default. Where is my miss?