I have a model:
class Detail(models.Model):
types_choices = (
(1, 'Sport'),
(2, 'Turbo'),
(3, 'Turbo++'),
)
car = models.ForeignKey(Car)
d_type = models.PositiveIntegerField(choices=types_choices, max_length=1)
def __unicode__(self):
return u"%s, %s" % (self.car.name, types_choices[self.d_type][1])
In admin interface there is a error: global name 'types_choices' is not defined. I think it about my return. How to fix it? I need car name and 'sport'(or turbo, etc.) in one string in admin interface.
Thanks.
you forgot the self.
class Detail(models.Model):
types_choices = (
(1, 'Sport'),
(2, 'Turbo'),
(3, 'Turbo++'),
)
car = models.ForeignKey(Car)
d_type = models.PositiveIntegerField(choices=types_choices, max_length=1)
def __unicode__(self):
return u"%s, %s" % (self.car.name, self.types_choices[self.d_type][1])
You should use self.get_d_type_display().
You should use self.types_choices. This is because types_choices is a property on your
Detail class.
Django docs have a good pattern on how to use choices: https://docs.djangoproject.com/en/dev/ref/models/fields/#choices
You can also use self.get_d_type_display() to get the verbose name of the choice field.
Related
I have created the following Django Model and I am trying to initialize one field - points - with the total number of instances of that same model, that is:
class Task(models.Model):
DEFAULT_VALUE = 5
description = models.CharField(max_length=60)
points = self.total() * DEFAULT_VALUE
STATUS = (('A', 'Active'), ('C', 'Cancelled'), ('D', 'Done'))
status = models.CharField(max_length=1, choices=STATUS, default='A')
def total(self):
count_active = len(Task.objects.filter(status='A'))
return count_active
In the python manage.py shell I can create two instances of Task and I can determine the total number of the instances that have been created with len(Task.objects.filter(status='A'))), however, when I try to implement this same code into a function then I encounter that self is an unresolved reference. What did I miss?
Solution: Write a function, which provides default value to the field
from django.apps import apps
def get_points():
Task = apps.get_model(app_label='your_app_name', model_name='Task')
return Task.objects.filter(status='A').count() * Task.DEFAULT_VALUE
class Task(models.Model):
DEFAULT_VALUE = 5
STATUS = (('A', 'Active'), ('C', 'Cancelled'), ('D', 'Done'))
description = models.CharField(max_length=60)
points = models.IntegerField(null=True, blank=True, default=get_points)
status = models.CharField(max_length=1, choices=STATUS, default='A')
What I've done here??
I've created a IntegerField to store the points data with a default parameter, which is a callable default function.
Use class method:
class Task(models.Model):
...
#classmethod
def total(cls, status=None):
return cls.objects.filter(status=status).count()
Usage:
Task.total('A')
class Task(models.Model):
...
#staticmethod
def total():
return len(Task.objects.filter(status='A'))
And in shell you can call this method from class or instance:
Task.total() or task = Task(*some_arguments); task.total()
How do you call the function? I have many properties with the same estructure and all works. But you have to instance the Task. For example I have this code:
#property
def is_expired(self):
now = timezone.now()
td = now - self.creation_time
_seconds = td.total_seconds()
validity_last = _seconds / 3600
if validity_last < self.validity_minutes:
return False
return True
To call it I have to make an instance of the model:
obj = ModelObject.objects.get(pk=1)
obj.is_expired()
Yours have the same structure so the code seems ok.
I'm looking to return a str on this model that is equal to industry name + risk level (i.e. Low)
RISKLEVEL = (
(0, "Low"),
(1, "Medium"),
(2, "High"),
)
class IndustryIndex(models.Model):
industry = models.CharField(max_length=200)
risk = models.IntegerField(choices=RISKLEVEL)
description = models.CharField(max_length=200)
def __str__(self):
return self.industry + self.page
I know that my syntax on the line under def __str__(self): isn't correct. Do you know what it should be? Also, self.page only seems to return the integer, but I'm interested in returning the description (i.e. 'High').
Thanks!
You can use get_risk_display() method:
def __str__(self):
return '{}-{}'.format(self.industry, self.get_risk_display())
On the template, when I call person.health_issue, I am getting '1','2' instead of 'Abdominal pain','Anaphylaxis'. How to display the value ('Abdominal pain','Anaphylaxis') instead of the code(1 or2 etc).
I tried with this also {{ person.get_health_issue_display }} in template,it is not displayed anything.
forms.py
HEALTH_USSUES = (
('1', 'Abdominal pain'), ('2', 'Anaphylaxis'), ('3', 'Asthma'),
('4', 'Bruising'), ('5', 'Chest pains'), ('6', 'Coughs or Colds')
)
class PersonActionsForm(forms.ModelForm):
action = forms.MultipleChoiceField(widget=forms.Select(), choices=HEALTH_USSUES, required=False)
models.py
class ReportPerson(models.Model):
report = models.ForeignKey(Report)
name = models.CharField('Name', max_length=100)
first_aid = models.BooleanField('First aid', default=False)
health_issue = models.IntegerField(default=0)
views.py
def report_template(request):
""""""
person = ReportPerson.objects.get(pk=person_id)
""""""
return render(request, 'event/print.html',
{
'person':person
})
can any one tell me how to do this.
Thanks
As you don't have any choices set in model field health_issue you need to write the get_health_issue_display method by your self i will name it as health_issue_display so that default get_FOO_display method not gets overridden:
HEALTH_USSUES = (
(1, 'Abdominal pain'), (2, 'Anaphylaxis'), (3, 'Asthma'),
(4, 'Bruising'), (5, 'Chest pains'), (6, 'Coughs or Colds')
)
class ReportPerson(models.Model):
report = models.ForeignKey(Report)
name = models.CharField('Name', max_length=100)
first_aid = models.BooleanField('First aid', default=False)
health_issue = models.IntegerField(default=1)
def health_issue_display(self):
for c in HEALTH_USSUES:
if c[0] == self.health_issue:
return c[1]
Or just add choices in the model field:
health_issue = models.IntegerField(default=1, choices=HEALTH_USSUES)
Now you have get_health_issue_display.
Also make the first value in every choice as integer (1, 'Abdominal pain') rather than string '1'. Just to remove the confusion.
You have default=0 which does not exists in choices. Change it to default=1
I have three classes
Class Company(models.Model):
name = CharField( max_length = 26 , blank = True)
#(...)
class Person(models.Model):
name = CharField( max_length = 26 , blank = True)
function = CharField( max_length = 50 , blank = True)
company = ForeignKey ( Company , related_name = 'persons' )
# All the company table inside the data base is loaded in order to make the query,
# This make a HUGE amount of data and takes too many time...
# (...)
def __unicode__(self):
# caption uses both name and company__name fields but no other fields
return self.name + '(' + self.company.name + ')'
class Contact(models.Model):
person = ForeignKey ( Person )
In order to optimise performances, I would like the latest person field to use
Person.objects.all().only('name', 'company__name')
as queryset. Is it possible?
You can use values method, which return a subclass of QuerySet called ValuesQuerySet.
Person.objects.all().values('name', 'company__name')
For more information Django Doc
Use proxy models :
class Person_short_manager(Manager):
def get_query_set(self):
return super(self, Person_short_manager).get_query_set().only('name','company__name')
class Person_short(Person):
objects = Person_short_manager(Manager)
class Meta:
proxy = True
then replace
person = ForeignKey ( Person )
by
person = ForeignKey ( Person_short )
I have the following model
class Trivias(models.Model):
GIFT_CHOICES = (
('gas', 'Gasolina'),
('money', 'Dinero'),
('xp','Experiencia'),
)
NUMQ_CHOICES = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
)
idtrivias = models.IntegerField(primary_key=True)
url = models.CharField(max_length=450)
numQ = models.IntegerField(max_length=4,choices=NUMQ_CHOICES)
idtipospropiedades = models.ForeignKey(Tipospropiedades, db_column='idtipospropiedades')
idtitulos = models.ForeignKey(Titulos, db_column='idtitulos')
correct = models.IntegerField(max_length=1)
gift = models.CharField(max_length=5,choices=GIFT_CHOICES)
value = models.CharField(max_length=20)
class Meta:
db_table = u'trivias'
I want the url field has a default value in the Django Admin, How I can do?
regards
Is there any reason you're storing the URL as a CharField rather than a URLField? URLField is a URL-specific subclass of CharField. Also, to set default values, use default="x", e.g.
url = models.URLField(default='http://www.foo.com')
Hope that helps.