Python's unicode - python

I have the following:
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=200)
def _unicode_(self):
return self.name
class Item(models.Model):
category = models.ForeignKey(Category)
dateadded = models.DateTimeField('date added')
name = models.CharField(max_length=200)
description = models.TextField()
quantity = models.IntegerField()
My problem is that def _unicode_(self) isn't working. Any ideas?

you should use def __unicode__

Related

How can I implement the same widget that Django uses to ManyToMany fields in the admin page?

My models:
class Ingredient(models.Model):
BASE_UNIT_CHOICES = [("g", "Grams"), ("ml", "Mililiters")]
CURRENCY_CHOICES = [("USD", "US Dollars"), ("EUR", "Euro")]
ingredient_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
base_unit = models.CharField(max_length=2, choices=BASE_UNIT_CHOICES)
cost_per_base_unit = models.FloatField()
currency = models.CharField(
max_length=3, choices=CURRENCY_CHOICES, default="EUR")
def __str__(self):
return self.name
class RecipeIngredient(models.Model):
quantity = models.FloatField()
ingredient_id = models.ForeignKey(Ingredient, on_delete=models.CASCADE)
def __str__(self):
return f"{self.quantity} / {self.ingredient_id}"
class Recipe(models.Model):
recipe_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=200)
ingredients = models.ManyToManyField(RecipeIngredient)
date_created = models.DateTimeField('Date Created')
def __str__(self):
return f"{self.name}, {self.ingredients}"
When I use the admin page, it has this + button that allows me to create new ingredient/quantity combinations
like this
But when I try to use it from a form in my code it looks like
this
Here is my form code:
class AddRecipeForm(forms.ModelForm):
class Meta:
model = Recipe
fields = ['name', 'ingredients', 'date_created']
You should write the 'widgets' for each field in you Form that need configuration.
Check the documentation 'Widgets in forms', or even, you can define your own Widgets.

relationships in django 2 models.py

I want to define a relationship between Book and Member through Borrow in models.py
ER
But I don't know how to define the Borrow relationship.
In the Borrow table it must be determined which books have been borrowed by who and which books have been returned on which date. Should I use another table for this date field?
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext as _
class CategoryType(models.Model):
category_name = models.CharField(max_length=200)
def __str__(self):
return self.category_name
class Book(models.Model):
name = models.CharField(verbose_name="عنوان", max_length=128)
number_of_copy = models.IntegerField(default=0)
writer = models.CharField(max_length=64)
B_category = models.ForeignKey(CategoryType, on_delete=models.CASCADE)
class Meta:
ordering = ["B_category"]
def __str__(self):
return self.name
class Borrow(models.Model):
borrowed_from_date = models.DateField(_("borrow Date"), default=0)
borrowed_to_date = models.DateField(_("return Date"), default=3)
actual_return_date = models.DateField()
borrowed_by = models.ForeignKey(member, on_delete=models.CASCADE)
books = models.ManyToManyField(Book)
def __str__(self):
return self.id
class Member(AbstractUser):
pass
I think in the Member class I should have a field containing borrow_id, but how?
It seems to me that you need to use a ManyToMany relationship with a through model (this way you can store extra information for every row of the Borrow model)
...
class Borrow(models.Model):
borrowed_from_date = models.DateField(_("borrow Date"), default=0)
borrowed_to_date = models.DateField(_("return Date"), default=3)
actual_return_date = models.DateField()
borrowed_by = models.ForeignKey(Member, on_delete=models.CASCADE)
book = models.ForeignKey(Book)
def __str__(self):
return self.id
...
class Member(AbstractUser):
borrowed_books = models.ManyToManyField(Book, through='Borrow')
Maybe this link (https://docs.djangoproject.com/es/2.1/ref/models/fields/#django.db.models.ManyToManyField.through) could clarify it more.

Import CSV file to Django models

I have one CSV file and I want to import the content of this file to my Django Models, can someone help me and explain how can I do this?
This is my CSV.
NAME,CLUB,LEAGUE,POSITION,RATING,PACE,SHOOTING,PASSING,DRIBBLING,DEFENDING,PHYSICAL,LOADDATE
Aleksandar Kolarov,Roma,Calcio A,LB,81,72,68,72,64,84,85,2018-04-14 08:37:48
And my models are;
class Player(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=128)
league = models.ForeignKey('League', on_delete=models.CASCADE)
club = models.ForeignKey('Club', on_delete=models.CASCADE)
attributes = models.ForeignKey('Attribute', on_delete=models.CASCADE)
def __str__(self):
return self.name
class League(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Club(models.Model):
name = models.CharField(max_length=30)
league = models.ForeignKey('League', on_delete=models.CASCADE)
def __str__(self):
return self.name
class Attribute(models.Model):
pace = models.IntegerField()
shooting = models.IntegerField()
passing = models.IntegerField()
dribbling = models.IntegerField()
defending = models.IntegerField()
physical = models.IntegerField()
position = models.CharField(max_length=4)
overall = models.IntegerField()
def __str__(self):
return '%s %s'%(self.overall, self.position)
If you want to do this action in django admin, you can follow these steps:
1.install
pip install django-import-export
2.update settings.py file
INSTALLED_APPS = (
'import_export',
)
3.add this in admin.py file
from import_export.admin import ImportExportModelAdmin
class PlayerAdmin(ImportExportModelAdmin):
list_display = ('name', )
admin.site.register(Player, PlayerAdmin)

How django aggregation with foreign key work?

I have a model:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Publisher(models.Model):
name = models.CharField(max_length=300)
num_awards = models.IntegerField()
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
pubdate = models.DateField()
class Store(models.Model):
name = models.CharField(max_length=300)
books = models.ManyToManyField(Book)
registered_users = models.PositiveIntegerField()
I could not understand how the following code work
This is from the django official Documentation, in the cheat sheet.
https://docs.djangoproject.com/en/1.10/topics/db/aggregation/
What I am trying to do is count the total votes for the following model
I use Question.objects.filter(owner_id=1).annotate(total_votes=Sum('votes')) as in the documentation. But this not work for me.
class Question(models.Model):
question_text = models.CharField('Question',max_length=200)
pub_date = models.DateTimeField('date published')
owner = models.ForeignKey(User,default=DEFAULT_USER_ID)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
Your Question model doesn't have votes your Choice model does
Question.objects.filter(owner_id=1).annotate(total_votes=Sum('choice__votes'))

Related to model( each song need each artist)

I have created this model. But I need each song need each artist How Is it possible?
I have no idea. Here is my model screenshot Can you please help me ? thank you
class Song(models.Model):
title = models.CharField(max_length=100,help_text="Album Name")
slug = models.SlugField(unique = True,help_text="Must be unique.")
artist = models.CharField(max_length=100)
song_1 = models.CharField(max_length=100)
song_2 = models.CharField(max_length=100)
song_3 = models.CharField(max_length=100)
song_4 = models.CharField(max_length=100)
song_5 = models.CharField(max_length=100)
song_6 = models.CharField(max_length=100)
#
type = models.ForeignKey(Category)
def __unicode__(self):
return self.title
UPDATE2: Thank guys. I think its not right solution. If I have to found song_5 is belong to this album and to this artist. How is it possible? :-?
class Artist(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Album(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Song(models.Model):
song_1 = models.CharField(max_length=100)
song_2 = models.CharField(max_length=100)
song_3 = models.CharField(max_length=100)
song_4 = models.CharField(max_length=100)
song_5 = models.CharField(max_length=100)
song_6 = models.CharField(max_length=100)
#
artist = models.ManyToManyField(Artist)
album = models.ManyToManyField(Album)
type = models.ForeignKey(Category)
def __unicode__(self):
return self.title
In the Song class, add a field:
artist = models.ForeignKey(Artist)
Then each song will have only one artist, but the artists can have many songs. If you want a song to have many artists, use ManyToManyField.
You have to create relations between artists, songs and albums.
In your case a ForeignKey ist probably sufficient, but as
this is really a broad and fundamental topic you should definitely read the docs on Relationships.
The best Solution is InlineModel. Here is link https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin
Thanks anyways. Here is my output
Here is My model
class Artist(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Album(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Song(models.Model):
title = models.CharField(max_length=100)
artist = models.ForeignKey(Artist)
album = models.ForeignKey(Album)
type = models.ForeignKey(Category)
def __unicode__(self):
return self.title
here is admin.py
class SongInline(admin.TabularInline):
#list_display = ('title','artist','song_1','song_2','song_3','song_4','song_5','song_6')
#prepopulated_fields = { 'slug': ['title'] }
model = Song
class AlbumAdmin(admin.ModelAdmin):
inlines = [
SongInline,
]
class ArtistAdmin(admin.ModelAdmin):
pass

Categories