Related to model( each song need each artist) - python

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

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.

Getting the entries of a ManyToManyField

I'm working with a ManyToManyField and using a ModelMultipleChoice on form, I want to get the entries, but all I get is appname.Extra.none
models.py
class Extra(models.Model):
extra_n = models.CharField(max_length=200)
extra_price = models.IntegerField(default=0)
def __str__(self):
return self.extra_n
class Meal(models.Model):
restaurant = models.ForeignKey(Restaurant, on_delete=models.PROTECT)
category = models.ForeignKey(MealCategory, on_delete=models.PROTECT)
name = models.CharField(max_length=500)
short_description = models.CharField(max_length=500)
image = models.ImageField(upload_to='meal_images/', blank=False)
price = models.IntegerField(default=0)
extras = models.ManyToManyField(Extra, related_name='extras')
def __str__(self):
return self.name
forms.py
class MealForm(forms.ModelForm):
extras = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Meal.extras)
class Meta:
model = Meal
exclude = ("restaurant",)
views.py
def restaurant_meal(request):
meals = Meal.objects.filter(restaurant = request.user.restaurant).order_by("-id")
return render(request, 'restaurant/meal.html', {"meals": meals})
The output desired is getting the extras added displayed on restaurant_meal view.
you can try change
meals = Meal.objects.filter(restaurant = request.user.restaurant).order_by("-id")
to
meals = Meal.objects.filter(restaurant = request.user.restaurant).prefetch_related('extras').order_by("-id")
and try again.
Doc of this in prefetch_related

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)

Django- limit_choices_to using 2 different tables

I fear that what I am trying to do might be impossible but here we go:
Among my models, I have the following
Class ParentCategory(models.Model):
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
Class Category(models.Model):
parentCategory = models.ForeignKey(ParentCategory, on_delete=models.CASCADE, )
name = models.CharField(max_length=128)
def __unicode__(self):
return self.name
Class Achievement(models.Model):
milestone = models.ForeignKey(Milestone, on_delete=models.CASCADE)
description = models.TextField( )
level_number = models.IntegerField()
completeion_method = models.ForeignKey(Category, on_delete = models.CASCADE, limit_choices_to={'parentCategory.name':'comp method'})
def __unicode__(self): # TODO:
return description[0,75] + '...'
I know the completion method field throws an error because it is not correct syntax. But is there a way to achieve the wanted result using a similar method?
Maybe this will work:
limit_choices_to={'parentCategory__name': 'comp method'}

Python's unicode

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__

Categories