I am using a ForeignKey called Memberno in My Django models. After entering data in the Members Class, it appears in the other classes as "member object" in the 'memberno' field. For ForeignKey, I am using 'raw_id_fields' as a workaround, but for normal fields and even 'filter_horizontal' , each memberno value is displayed as "member object". I would like the values to appear as they are in the member class i.e. 1, 2, ...
from django.db import models
# Create your models here.
class Members(models.Model):
DESIGNATION_CHOICES=(
('ADM', 'Administrator'),
('OFF', 'Club Official'),
('MEM', 'Ordinary Member'),
)
memberno = models.AutoField(primary_key=True)
fname = models.CharField(max_length=15)
sname = models.CharField(max_length=15)
onames = models.CharField(max_length=30, blank=True)
email = models.EmailField()
phoneNumber = models.CharField(max_length=15)
regNo = models.CharField(max_length=15)
designation = models.CharField(max_length=3,choices=DESIGNATION_CHOICES)
image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True)
course = models.CharField(max_length=30, blank=True, null=True)
def __unicode__(self):
return u'%s %s %s' % (self.fname, self.sname, self.memberno)
def get_absolute_url(self):
return '%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.id)
def get_download_url(self):
return '%s%s/%s' % (settings.MEDIA_URL, settings.ATTACHMENT_FOLDER, self.name)
class Security(models.Model):
memberno = models.ForeignKey(Members, unique=True)
username = models.CharField(max_length=30, primary_key=True)
password = models.CharField(max_length=70)
def __unicode__(self):
return u'%s %s %s' % (self.username, self.password, self.memberno)
class Subscriptions(models.Model):
memberno = models.ForeignKey(Members)
receiptNo = models.CharField(max_length=30, primary_key=True)
type = models.CharField(max_length=50)
date = models.DateField()
amount = models.FloatField(max_length=99)
def __unicode__(self):
return u'%s %s %s' % (self.receiptno, self.type, self.memberno)
class events(models.Model):
eventName = models.CharField(max_length=25)
eventID = models.AutoField(primary_key=True)
details = models.TextField()
attendanceFee = models.FloatField(max_length=99)
date = models.DateField()
memberno = models.ManyToManyField(Members)
def __unicode__(self):
return u'%s %s %s' % (self.eventName, self.eventID, self.memberno)
The admin interface appears to use __str__() to determine the display of a model. I make it a habbit to always define both __unicode__() and __str__() when I create a model. For example:
class Activity(models.Model):
activity_code = models.ForeignKey(ActivityCode)
note = models.TextField(blank=True)
def __str__(self):
return "(%s) %s" % (self.activity_code.short, self.note)
def __unicode__(self):
return u'(%s) %s' % (self.activity_code.short, self.note)
Update:
It looks as though your def __unicode__(self) is not indented properly in your code. As a result it is not a part of your class, and is not being used. Indenting is very important in Python.
I am not sure I understand your question completely, but have you defined a unicode method for your models?
Related
I am trying to understand how exactly query works on Django, i followed the tutorials it´s not working I am not sure what i am doing wrong.
When I run
BeneficientePagar.objects.filter(nome__contains="Joao Pedro")
it returns
"Choices are %s" %s (name, ",".join(available))) django.core.exceptions.FieldError: Cannot resolve keyword "nome into field. Choices are: ID, beneficiente, beneficiente_id,join, join_id, moeda
from django.db import models
# Create your models here.
class Moeda(models.Model):
moeda_ficticia = models.FloatField()
class Join(models.Model):
nome = models.CharField(max_length=150)
nascimento = models.DateField()
cpf = models.IntegerField(primary_key=True)
endereco = models.CharField(max_length=150)
email = models.EmailField()
def __str__(self):
return self.nome
class Beneficiente(models.Model):
ID = models.AutoField(primary_key=True)
nome = models.CharField(max_length=150)
CNPJ = models.IntegerField(max_length = 10)
def __str__(self):
return self.nome
class Favores(models.Model):
ID = models.AutoField(primary_key=True)
favor = models.CharField(max_length=150)
dataInserido = models.DateField()
usuarios = models.ForeignKey(Join)
def __str__(self):
return self.favor
class BeneficientePagar(models.Model):
ID = models.AutoField(primary_key=True)
moeda = models.IntegerField()
beneficiente = models.ForeignKey(Beneficiente)
join = models.ForeignKey(Join)
def __str__(self):
return self.ID
Thanks in advance
If using BeneficientPager, you need to do
BeneficientePagar.objects.filter(beneficient__nome__contains="Joao Pedro")
You are getting the error because nome is a field on Beneficiente, not BeneficientePagar.
You can either do
Beneficiente.objects.filter(nome__contains="Joao Pedro")
which will return a queryset of Beneficientes. Or if you need BeneficientePagar you can query through the foreign key.
BeneficientePagar.objects.filter(beneficiente__nome__contains="Joao Pedro")
My models.py:
from django.db import models
class OgretimElemani(models.Model):
adi = models.CharField(max_length=50)
soyadi = models.CharField(max_length=50)
telefonu = models.CharField(max_length = 10 , blank=True)
e_posta_adresi = models.EmailField(blank=True)
def __unicode__(self):
return '%s %s' % (self.soyadi,self.adi)
class Ders(models.Model):
kodu = models.CharField(max_length=10)
adi = models.CharField(max_length=50)
ogretim_elamani = models.ForeignKey(OgretimElemani)
tanimi = models.CharField(max_length=1000,blank = True)
def __unicode__(self):
return '%s %s %s' % (self.kodu,self.adi,self.ogretim_elamani)
class Ogrenci(models.Model):
numarasi = models.IntegerField()
adi = models.CharField(max_length=50)
soyadi = models.CharField(max_length=50)
aldigi_dersler = models.ManyToManyField(Ders)
def __unicode__(self):
return '%s %s %s' % (self.soyadi,self.adi,self.aldigi_dersler)
Django shell :
>>>ders1=Ders(kodu='KIM101', adi='Kimya-1')
>>>ders1.ogretim_elemani=OgretimElemani[0]
>>>ders1.save()
IntegrityError : yonetim_ders.ogretim_elemani_id may not be NULL
You must assign a OgretimElemani instance that has already been saved to the database.
For example, the following should work.
>>> ders1 = Ders(kodu='KIM101', adi='Kimya-1'
>>> ogretim_elemani = OgretimElemani.objects.all()[0] # fetch the first one from the database
>>> ders1.ogretim_elemani = ogretim_elemani
>>>ders1.save()
Your example is not very clear because you use OgretimElemani[0]. You shouldn't reuse the variable name OgretimElemani, it makes the code confusing.
It's quite hard for me to explain what i need with words so I here is some code:
class Configuration(models.Model):
name = models.CharField(max_length=250)
firmware_version = models.ForeignKey(FirmwareVersion)
devices_amount = models.PositiveIntegerField()
def __unicode__(self):
return unicode(self.name)
class Firmware(models.Model):
name = models.CharField(max_length=250)
circuit_model = models.ForeignKey(Versiiplates)
def __unicode__(self):
return unicode(self.name)
class FirmwareVersion(models.Model):
firmware = models.ForeignKey(Firmware)
version = models.CharField(max_length=100)
file = models.FileField(upload_to="firmware/")
upload_date = models.DateField(default = datetime.date.today())
notes = models.TextField(max_length=2500, null=True, blank=True)
def __unicode__(self):
return u'%s %s' % (self.firmware.__unicode__(), self.version)
Is there any way to choose in admin change-form for Configuration the Firmware first and then any FirmwareVersion related to it?
It's really simple to implement this behavior with django-smart-selects. In my case Configuration class should look like this:
class Configuration(models.Model):
name = models.CharField(max_length=250)
firmware = models.ForeignKey(Firmware, related_name="firmware")
firmware_version = ChainedForeignKey(FirmwareVersion, chained_field="firmware", chained_model_field="firmware", show_all="False", auto_choose=True)
devices_amount = models.PositiveIntegerField()
def __unicode__(self):
return unicode(self.name)
I have a base model, and proxy models. I want to change value of upload_to of 'image' filed, that depends on 'file_type' filed.
I'm not sure how to do this, do I need to specify it in my .Manager class or in Proxy class.
Can you please give me same detail how to do this.
class FileDescription(models.Model):
class Meta:
ordering = ['file_creation_time']
TYPE_CHOICES = (
('homework', 'Homework'),
('class', 'Class Papers'),
('random', 'Random Papers')
)
subject = models.ForeignKey('Subjects', null=True, blank=True, primary_key=True)
subject_name = models.CharField(max_length=100, unique=False)
file_type = models.CharField(max_length=100, choices=TYPE_CHOICES)
....
....
image = models.ImageField(upload_to= ??????????? blank=True, null=True, max_length=255)
def __unicode__(self):
return u'%s' % (self.file_name)
class HomeworkManager(models.Manager):
def get_query_set(self):
qs = super(HomeworkManager, self).get_query_set().filter(file_type='homework')
return qs
class ClassPapersManager(models.Manager):
def get_query_set(self):
qs = super(HomeworkManager, self).get_query_set().filter(file_type='class')
return qs
class RandomPapersManager(models.Manager):
def get_query_set(self):
qs = super(HomeworkManager, self).get_query_set().filter(file_type='random')
return qs
class Homework(FileDescription):
class Meta:
proxy = True
Don't worry about replacing upload_to just modify the method to handle different subclasses (use a method for upload_to if you're not already).
def my_upload_to(instance, filename):
if instance._meta.module_name == 'homework':
return '/path/to/homework/files/%s' % filename
if instance._meta.module_name == 'classpaper':
return '/path/to/classpaper/files/%s' % filename
if instance._meta.module_name == 'randompaper':
return '/path/to/randompaper/files/%s' % filename
I have two models :
class Album(models.Model):
#Attributes
title = models.CharField(max_length=200)
displayed = models.BooleanField()
created_on = models.DateTimeField(auto_now_add=True)
class Photos(models.Model):
#Attributes
title = models.CharField(max_length=500)
link = models.CharField(max_length=500)
album = models.ForeignKey(Album, unique=False, verbose_name=_('album'))
def upload_path(self, filename):
return 'upload/photos/%s/%s' % (self.id, filename)
def upload_path_thumbnail(self, filename):
return 'upload/photos/%s/%s' % (self.id, "thumnail_" +filename)
thumbnail = models.ImageField(upload_to=upload_path_thumbnail)
photo = models.ImageField(upload_to=upload_path)
created_on = models.DateTimeField(auto_now_add=True)
displayed = models.BooleanField()
And I want to force, when i select Photos, to always filter on displayed=1.
Thank you
Use a custom manager:
class DisplayedPhotoManager(models.Manager):
def get_queryset(self):
return super(DisplayedPhotoManager, self).get_queryset().filter(displayed=1)
class Photos(models.Model):
objects = DisplayedPhotoManager()
...
this will override standard "objects" manager (which can be dangerous).
A nicer pattern is often:
class DisplayedPhotoManager(models.Manager):
def get_queryset(self):
return super(DisplayedPhotoManager, self).get_queryset().filter(displayed=1)
class Photos(models.Model):
objects = models.Manager()
displayed = DisplayedPhotoManager()
...
and use 'displayed' instead of 'objects':
Photo.displayed.all()