Django creating model instances without keyword arguments - python

In Django, if you want to create a model you can do it as follows:
class SomeModel(models.Model):
a = models.CharField(max_length=10)
b = models.CharField(max_length=20)
c = models.CharField(max_length=30)
d = models.CharField(max_length=40)
e = models.CharField(max_length=50)
f = models.CharField(max_length=60)
Now if you want to create an instance in the shell, you have to do:
> abcdef = SomeModel(a="stuff", b="stuff", c="stuff", d="stuff", e="stuff", f="stuff")
This gets really annoying if you have to keep creating model instances with long property names. Is there a way to simply send the arguments like you would with a normal Python object (as in without having to name the variables and just send the variables in order) ?
Like this:
> abcdef = SomeModel("stuff", "stuff", "stuff", "stuff", "stuff", "stuff")
As you would with a standard Python class in the init function.
Thanks :)
Here is my actual Python model:
class School(models.Model):
urn = models.CharField(max_length=6)
name = models.CharField(max_length=100)
house = models.CharField(max_length=50)
street = models.CharField(max_length=50)
county = models.CharField(max_length=50)
postcode = models.CharField(max_length=8)
def __unicode__(self):
return str(
'URN: ' + self.urn + ', ' +
'Name: ' + self.name + ', ' +
'House: ' + self.house + ', ' +
'Street: ' + self.street + ', ' +
'County: ' + self.county + ', ' +
'Postcode: ' + self.postcode + ', '
)

Have you tried the following code:
obj = SomeModel(None, "a_stuff", "b_stuff", "c_stuff", "d_stuff", "e_stuff", "f_stuff")
obj.save()
Hope these helps.

you can create instance by doing
abcdef = SomeModel()
Since instantiating doesnot touch the database, you can assign values later and then do .save().

Related

Why does the add_student method in my Student class not work (It is saying requires additional argument but it only takes one)?

I created a simple Student list and wish to append manual student objects created, using the method below. It comes up with an error saying it requires an additional argument.
class Student:
def __init__(self, first_name, last_name, student_num, email, pps, middle_name):
self.first_name = first_name
self.last_name = last_name
self.student_num = student_num
self.email = email
self.__pps = pps
self.__middle_name = middle_name
self.student_list =[]
def get_full_details(self):
details = self.first_name + " " + self.last_name + " " + str(self.student_num) + " " + self.email
return details
def add_student(self, student_object):
return self.student_list.append(student_object)
# Creating 4 student objects
student1 = Student("Jimmy", "Mccarthy", 1234, "johnmc#gmail.com", 8074454, "Edward")
student2 = Student("James", "Flynn", 5678, "James#gmail.com", 7367736, "Borck")
student3 = Student("Emma", "Mcgath", 9837, "EMChammer#hotmail.com", 3455433, "Richei")
student4 = Student("Echo", "O Leary", 4334, "Echool#gmail.com", 4333357, "Wei")
Student.add_student(student1)
If you call Student.add_student, you need 2 arguments: self, student_object.
You can solve this if you first call the constructor of the class student1 = Student("Jimmy", "Mccarthy", 1234, "johnmc#gmail.com", 8074454, "Edward"), then use add_student on student1: student1.add_student(Student("James", "Flynn", 5678, "James#gmail.com", 7367736, "Borck")).

Practice to call a function inside itself

I have parent/child relation with tables. Looks like this.
class Person(models.Model):
Name = models.CharField()
class ParentChild(models.Model):
child = models.ForeignKey('Person', related_name='child')
parent = models.ForeignKey('Person', related_name='parent')
validfrom = models.DateTimeField(blank=True, null=True)
validto = models.DateTimeField(blank=True, null=True)
I am trying to query a whole tree and create a json to send to template.
So for each person I'm thinking of using a function to query the children, and for each children use same function to query if that child has any children.
So this is my function
def getChildren(parentID):
try:
children = Person.objects.filter(parent=parentID)
addJson = 'children: ['
for a in children:
addJson = addJson + '{text: { name: "Child '+str(a.id)+'" }},'
addJson = getChildren(str(a.id))
return addJson
except:
return addJson
This only gets me one child then nothing more. So I'm guessing it's not possible to invoke itself, or maybe a function have to finish before being called again.
I'm pretty stuck right now. Ideas are much welcome!
I solved the issue. I wasn't taking notice about that the query were for a PK in wrong table.
def getChildren(parentID, jsonData):
try:
qChildren = ParentChild.objects.filter(parent=parentID).values('child')
addJson = jsonData + 'children: ['
for a in qChildren:
addJson = addJson + '{text: { name: "Child ' + str(a['child']) + '" }},'
addJson = getChildren(str(a['child']), addJson)
addJson = addJson + ']'
return addJson
except:
return None

Django: Count users used in model's ManyToMany

Given a model:
class Workshop(models.Model):
title = models.CharField(max_length=40)
participants = models.ManyToManyField(User, null=True, blank=True)
(User is django.contrib.auth.models.User)
Users can be in more than one Workshop:
w1.participants = (u1, u2)
w2.participants = (u2, u3)
...
I need to find:1) Number of users participating in 1 workshop (u1, u3)2) Number of users participating in 2 workshop (u2)3) Number of users who don't participating in any workshop (u0)
Could anyone help me please?Thank you very much in advance!
Try this:
from django.db.models import Count
1)
User.objects.annotate(workshop_count=Count('workshop')).filter(workshop_count=1).count()
2)
User.objects.annotate(workshop_count=Count('workshop')).filter(workshop_count=2).count()
3)
User.objects.filter(workshop__isnull=True).count()
More info in the docs
This should do what you want:
workshop_user_dict = {}
user_objects = User.objects.all()
for user in user_objects:
workshops_count = user.workshop_set.all().count()
if not workshops_count in workshop_user_dict:
workshop_user_dict[workshops_count] = []
workshop_user_dict[workshops_count].append(user)
for key, list in workshop_user_dict.items():
print 'There are ' + str(len(list)) + ' users that are participating in ' + str(key) + ' workshops'

how to use a numeric field?

please help fix model .
from django.db import models
from sorl.thumbnail import ImageField
from decimal import *
class News (models.Model):
CHOICES_inner_image_position = [
(Decimal ("10.5"), '10 .5% '),
(Decimal ("17.5"), '17 .5% '),
(Decimal (" 30") , '30 % ')
(Decimal (" 33" ) , '33 % ')
]
         
title = models.CharField ( u'Zagolovok ', max_length = 70)
content = models.TextField (verbose_name = u'Soderzhanie ', max_length = 30000)
date_time = models.DateTimeField ()
image = models.ImageField (upload_to = 'news / headimage /')
public = models.BooleanField (verbose_name = u'Opublikovat news ? ', default = True)
teaser_length = DecimalField (verbose_name = u'Kolichestvo characters in the teaser ', max_digits = 4 , decimal_places = 0)
inner_image_position = like = forms.ChoiceField (choices = CHOICES_inner_image_position, widget = forms.RadioSelect ())
class Meta:
verbose_name = ' News '
verbose_name_plural = ' News '
I do a console command python manage.py syncdb and get the following error message:
NameError: name 'DecimalField' is not defined
django1.6
You're missing a models in front of your DecimalField. The line should read:
teaser_length = models.DecimalField(verbose_name = u'Kolichestvo characters in the teaser ', max_digits = 4, decimal_places = 0)

Invoking __unicode__ method

New to python, and trying to use __unicode_ to render a string representation. The code is part of Django model. How can I write __unicode__ of MyType so that in templates it output its representation as 123 - 123 South ....
class UsAddress(models.Model):
#other fields
zip = us_models.USPostalCodeField()
country = models.CharField(max_length=2)
phone = us_models.PhoneNumberField()
def __unicode__(self):
return self.zip + self.country + self.phone
class MyType(models.Model):
code = models.IntegerField()
address = UsAddress
def __unicode__(self):
return str(self.code) + " - " + unicode(self.address) #self.address.__unicode__()
Output:
<MyType: 219 - <class 'web.models.UsAddress'>>
EDIT
At least in my case, the problem was I didn't model the relationship. So I added it to UsAddress.
mt = models.ForeignKey(MyType)
Try this:
class MyType(models.Model):
code = models.IntegerField()
address = UsAddress
def __unicode__(self):
return u'%s - %s' % (self.code, self.address)
Here is the unicode method.
Then, you can just use it in your template like this:
<p>My object: {{ mytype_obj }}</p>
The output will be:
My object: 123 - 123 South ....

Categories

Resources