Consider the following model :
from django.db import models
class Album(models.Model):
id = models.IntegerField(primary_key=True,null=False)
artist = models.CharField(max_length=200)
album_title = models.CharField(max_length = 250)
genre = models.CharField(max_length=100)
album_logo = models.CharField(max_length = 200)
def __str__(self):
return "id = " + str(self.id) + " artist = " + self.artist + " album = " + self.album_title + " genre = " + self.genre
class Song(models.Model):
id = models.IntegerField(primary_key=True)
album = models.ForeignKey(Album,on_delete=models.CASCADE)
file_type = models.CharField(max_length = 200)
song_title = models.CharField(max_length = 200)
def __str__(self):
return "id = " + str(self.id) + "album = " + self.album.album_title + "song = " + self.song_title
When i am inserting a row in either Album or Song using positional parameters and not giving, django is providing NULL to that particular row. Why so?
First of all, there is no need of explicitly declaring a field named 'id' as Django already creates an id field with every model by default and auto-increments it.
In any case, if you want to deliberately declare a primary key it is recommended do it in the following manner:
id = models.AutoField(primary_key=True)
This is an auto-incrementing primary key.
Reference Official Django Docs:
https://docs.djangoproject.com/en/1.11/topics/db/models/#automatic-primary-key-fields
Related
My Models
class ServicesMenu(models.Model):
category = models.CharField(max_length=200)
class Varient(models.Model):
category = models.ForeignKey(ServicesMenu, on_delete=models.CASCADE)
varient_Name = models.CharField(max_length=200)
class VarientSubField(models.Model):
select_Varient = models.ForeignKey(Varient, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
so the problem is in VariantSubField, its display something like this.
here some value are similar i cant change them but i need is to display "category" from ServicesMenu with these VariantSubField dropdown fields.
To customize dropdown text, you should implement the standard _ _ str _ _ method in the relevant model:
class VarientSubField(models.Model):
select_Varient = models.ForeignKey(Varient, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
def __str__(self):
return self.select_Varient.category + " - " + self.select_Varient.varient_name + " - " + self.name
I wrote a simple string generator for my order_id field.
I tested the generator script in shell, and it works perfectly.
But when I run the server, and try to create an order in django admin, the order id field remains empty when I click save.
What am I doing wrong?
from datetime import date
from django.db import models
from django.db.models.signals import pre_save
from cartapp.models import Cart
class Order(models.Model):
order_id = models.CharField(max_length=120)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
status = models.CharField(max_length=50, default='Waiting', null=True, blank=True)
order_total = models.DecimalField(default=0.0, max_digits=10, decimal_places=1)
date_created = models.DateTimeField(auto_now_add=True)
def order_id_generator(instance):
today = date.today().strftime("%Y-%m-%d")
last_order_raw = Order.objects.latest('order_id').date_created
last_order_date = str(last_order_raw).split(' ')[0]
if today != last_order_date:
new_order_id = str(today + " 1")
else:
last_order = Order.objects.latest('order_id')
extract = last_order.order_id.split(' ')[1]
increment = int(extract) + 1
new_order_id = today + " " + str(increment)
return new_order_id
def pre_save_order_id(sender, instance, *args, **kwargs):
if not instance.order_id:
instance.order_id = order_id_generator(instance)
pre_save.connect(pre_save_order_id, sender=Order)
I noticed that you are passing instance to order_id_generator but doesn't use it there. You can avoid using signals and you can use your function as the model field default:
class Order(models.Model):
order_id = models.CharField(max_length=120, default=order_id_generator)
and you doesn't need an arg instance in your function:
def order_id_generator():
today = date.today().strftime("%Y-%m-%d")
last_order_raw = Order.objects.latest('order_id').date_created
last_order_date = str(last_order_raw).split(' ')[0]
if today != last_order_date:
new_order_id = str(today + " 1")
else:
last_order = Order.objects.latest('order_id')
extract = last_order.order_id.split(' ')[1]
increment = int(extract) + 1
new_order_id = today + " " + str(increment)
return new_order_id
Here is my models.py file.
from django.db import models
from django.contrib.auth.models import User
class image(models.Model):
name = models.CharField(max_length = 200)
src = models.URLField()
alt = models.CharField(max_length = 200)
points = models.IntegerField(default = 0)
id = models.CharField(max_length = 200, primary_key = True)
hotelId = models.IntegerField()
def __unicode__(self):
return self.name
class imagescore(models.Model):
user = models.ForeignKey(User)
image_id = models.CharField(max_length = 200)
score = models.IntegerField(default = 1)
createdTime = models.DateTimeField(auto_now_add =True)
def __unicode__(self):
if self.score < 0:
status = " rejected "
else:
status = "approved"
return (self.user+ status+ image_id)
pass
I would like to pass on to my template a table that is a result of the SQL Query:
select ei.id,ei.src, ei.hotelId , sum(score)
from eyeballing_image ei LEFT join eyeballing_imagescore eis on ei.id = eis.image_id
where user_id = request.user.id and ei.hotelId = 56565
group by
ei.id,ei.src, ei.hotelId
My app name is eyeballing. O tried using joins and filters bot i couldn't make it work.
Additionally, i tried making the sum(score) part into a separate dict and check the same in the template. Didn't work
Any help will be appreciated.
Your query has two problems, one in column name hotelId. you must use it in query in this way ei."hotelId".
Other problem is in condition user_id = request.user.id because you have not request in sql and you must replace it with a value.
Maybe another problem is in return (self.user + status + image_id) that must be return (self.user + self.status + self.image_id).
I have the following models:
class LibraryEntry(models.Model):
player = models.ForeignKey(Player)
player_lib_song_id = models.IntegerField()
title = models.CharField(max_length=200)
artist = models.CharField(max_length=200)
album = models.CharField(max_length=200)
track = models.IntegerField()
genre = models.CharField(max_length=50)
duration = models.IntegerField()
is_deleted = models.BooleanField(default=False)
class Meta:
unique_together = ("player", "player_lib_song_id")
def __unicode__(self):
return "Library Entry " + str(self.player_lib_song_id) + ": " + self.title
class BannedSong(models.Model):
lib_entry = models.ForeignKey(LibraryEntry)
def __unicode__(self):
return "Banned Library Entry " + str(self.lib_entry.title)
I'd like to do a query like this:
banned_songs = BannedSong.objects.filter(lib_entry__player=activePlayer)
available_songs = LibraryEntry.objects.filter(player=activePlayer).exclude(banned_songs)
Basically if a song is banned, I want to exclude it from my set of available songs. Is there a way to do this in Django?
banned_song_ids = (BannedSong.objects.filter(lib_entry__player=activePlayer)
.values_list('lib_entry', flat=True))
available_songs = (LibraryEntry.objects.filter(player=activePlayer)
.exclude('id__in' = banned_song_ids))
The alternative is:
available_songs = (LibraryEntry.objects.filter(player=activePlayer)
.filter(bannedsong__isnull = True))
I get this error while running syncdb
Can't seem to figure out the issue. Please help.
Error: One or more models did not validate:
store.business: Reverse query name for field 'logo' clashes with field 'ImageBank.business'. Add a related_name argument to the definition for 'logo'.
Here are my models:
class Business(models.Model):
business_type = models.ManyToManyField(BusinessType)
business_service_type = models.ManyToManyField(ServiceType)
establishment_type = models.ForeignKey(EstablishmentType)
logo = models.ForeignKey(ImageBank, related_name = '%(class)s_logocreated',)
phone = PhoneNumberField()
address = models.ForeignKey(Address)
website = models.URLField()
name = models.CharField(max_length=64)
def __unicode__(self):
return self.name
class ImageBank(models.Model):
business = models.ForeignKey('Business', related_name='%(class)s_business')
image = models.ImageField(upload_to="images/bank")
def url(self):
return self.image.url
def __unicode__(self):
return unicode(self.business) + " : " + unicode(self.image)
Store Model:
class Store(models.Model):
business = models.ForeignKey(Business,null=True, related_name='business_creator_set')
condition = models.CharField(verbose_name='What do customers have to do?',max_length = 50)
reward = models.CharField(verbose_name='What do customers win?',max_length = 50)
display = models.BooleanField(default=True)
date_created = models.DateTimeField(default=datetime.now)
def __unicode__(self):
return self.condition + ", " + self.reward
Try doing something like this:
...
class ImageBank(models.Model):
business = models.ForeignKey('Business', related_name='%(class)s_business')
....
Also, if that doesn't work, try changing the related_name on the Business.logo field to something not logo_id. logo_id is what the database uses for the field and it may be having a conflict.