I have a model and I want to copy all of my data when copy function called and it make a copy of my books with new datetime I wrote this:
class Book(models.Model):
name = models.CharField(max_length=255)
created_date = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey('Author', on_delete=models.CASCADE)
def copy(self):
new_book = Book()
new_book.name = self.name
new_book.created_date = models.DateTimeField(auto_now_add=True)
new_book.author = self.author
new_book.save()
class Author(models.Model):
name = models.CharField(max_length=255)
but author won't copied well
Related
but when i run it i shows errors that it cant find the muscel_id i Muscel class, how can i show only the names. i ma trying to build a workout plan using django
class Days(models.Model):
day_name = models.CharField(max_length=60)
class Muscel(models.Model):
Muscel_name = models.CharField(max_length=60)
class Exercise(models.Model):
exercise_name = models.CharField(max_length=70)
class Basic(models.Model):
dagen_basic = models.ForeignKey(Days, related_name='days_basic', on_delete=models.CASCADE)
muskel = models.ForeignKey(Muscel.Muscel_name, related_name='muskel_basic',
on_delete=models.CASCADE)
exercise_name = models.ForeignKey(Exercise.exercise_name, related_name='exercise_name_basic',
on_delete=models.CASCADE)
reps = models.CharField(max_length=20)
sets = models.IntegerField()
try this:
class Muscel(models.Model):
muscel_name = models.CharField(max_length=60)
def __str__(self):
return self.muscel_name
add str on your Muscel model,
class Basic(models.Model):
......
muskel = models.ForeignKey(Muscel, related_name='muskel_basic',
on_delete=models.CASCADE)
exercise_name = models.ForeignKey(Exercise, related_name='exercise_name_basic',
on_delete=models.CASCADE)
......
remove .Muscel_name on ForeignKey
I would like to filter my plots objects on the fruit ex.pear. The Inputs are linked via a manytomany to the plots. This is the structure:
This is the data I get out of it:
What i would like to have:
result:
I tried the following:
plots = Plot.objects.filter(fruittype__fruit="Pear")
inputs = Input.objects.filter(plot__in=plots).distinct()
This gives me already a close solution for my problem but not what I want.
Now I only would like to filter out the other plots that still show up with apple.
models inputs:
class Product (models.Model):
type = models.ForeignKey(Type, on_delete=models.CASCADE)
product = models.CharField(max_length=70)
standaard_dosis = models.FloatField()
def __str__(self):
return self.product
class Input (models.Model):
datum = models.DateField()
plot = models.ManyToManyField(Plot)
def __str__(self):
return str(self.datum)
class ProductInputs (models.Model):
input = models.ForeignKey(Inputs, on_delete=models.CASCADE, default="")
product = models.ForeignKey(Product, on_delete=models.CASCADE, default="")
dosis = models.FloatField()
def __str__(self):
string = str(self.product)
return string
models plots:
class Fruit(models.Model):
fruit = models.CharField(max_length=30, primary_key=True)
def __str__(self):
return self.fruit
class Meta:
verbose_name_plural = "fruits"
class Fruittype(models.Model):
fruit = models.ForeignKey(Fruit, on_delete=models.CASCADE)
fruittype = models.CharField(max_length=30, primary_key=True)
def __str__(self):
return self.fruittype
class Meta:
verbose_name_plural = "fruitypes"
class Plot(models.Model):
name = models.CharField(max_length=30)
fruittype = models.ForeignKey(Fruittype, on_delete=models.CASCADE)
def __str__(self):
return str(self.fruittype.fruit) + " | " + self.name
class Meta:
verbose_name_plural = "plots"
Your Plot queryset is not going as deep as it should. I think you should change to something like this (although this is it's a bit of overkill)
plot_ids = Plot.objects.filter(fruittype__fruit__fruit="Pear").values_list('pk', flat=True)
or
plot_ids = Plot.objects.filter(fruittype__fruittype="Pear").values_list('pk', flat=True) # I don't know what fruittype is but I guess this would help you
Then your "inputs"
inputs = Input.objects.filter(plot__pk__in=plot_ids).distinct()
You might wanna try this as well:
from django.db.models import Prefetch
Input.objects.prefetch_related(
Prefetch('plot', queryset=Plot.objects.filter(fruittype__fruit__fruit="Pear"))
)
It worked with:
all_inputs=Input.objects.filter(plot__pk__in=plot_ids).distinct().prefetch_related(Prefetch('plot', queryset=Plot.objects.filter(fruittype__fruit__fruit="Pear")))
I have model as below, I need to get bookname as ForeignKey and it works on Django Admin but I also need pageCount related with bookPageCount to auto determine on Django Admin or on add new record. When I add new log to ReadList I want pageCount to define automatically depending on record selected from Book;
class Book(models.Model):
bookname = models.CharField(max_length=200, verbose_name='Kitap Adı')
bookAuthor = models.CharField(max_length=100, verbose_name='Yazar Adı')
bookPublisher = models.CharField(max_length=100, verbose_name='Yayın Evi')
bookPageCount = models.PositiveIntegerField(verbose_name='Sayfa Sayısı')
bookAddDate = models.DateField(verbose_name='Kitaplığa Eklenme Tarihi')
class Meta:
verbose_name = 'Kitap'
verbose_name_plural = 'Kitaplar'
class ReadList(models.Model):
bookName = models.ForeignKey('kitaplik.Book.bookname', related_name='bookName', on_delete=models.CASCADE, verbose_name='Kitap Adı')
readerName = models.ForeignKey('ogrenciler.Students.studentName', on_delete=models.CASCADE, related_name='readerName', verbose_name='Okuyan Kişi')
dateOfRead = models.DateField(verbose_name='Okuma Tarihi')
pageCount = models.ForeignKey('kitaplik.Book.bookPageCount', related_name='pageCount', on_delete=models.PROTECT, verbose_name='Sayfa Sayısı')
class Meta:
verbose_name = 'Okuma Günlüğü'
After first answer I imported post_save and reciever to models.py and it is now like this;
class Book(models.Model):
bookname = models.CharField(max_length=200, verbose_name='Kitap Adı')
bookAuthor = models.CharField(max_length=100, verbose_name='Yazar Adı')
bookPublisher = models.CharField(max_length=100, verbose_name='Yayın Evi')
bookPageCount = models.PositiveIntegerField(verbose_name='Sayfa Sayısı')
bookAddDate = models.DateField(verbose_name='Kitaplığa Eklenme Tarihi')
class Meta:
verbose_name = 'Kitap'
verbose_name_plural = 'Kitaplar'
def __str__(self):
return self.bookname
class ReadList(models.Model):
bookName = models.ForeignKey('Book', related_name='book', on_delete=models.CASCADE, verbose_name='Kitap Adı')
readerName = models.ForeignKey('ogrenciler.Students', on_delete=models.CASCADE, related_name='readerName', verbose_name='Okuyan Kişi')
dateOfRead = models.DateField(verbose_name='Okuma Tarihi')
pageCount = models.PositiveIntegerField(verbose_name='Sayfa Sayısı',blank=True, null=True)
class Meta:
verbose_name = 'Okuma Günlüğü'
#receiver(post_save, sender=ReadList)
def get_pageCount(sender, instance, **kwargs):
instance.pageCount = instance.book.pageCount
instance.save
Maybe, can you write a more concise code, using the ForeignKey without repeating the fields.
class ReadList(models.Model):
book = models.ForeignKey('kitaplik.Book', related_name='book', on_delete=models.CASCADE, verbose_name='Kitap Adı')
readerName = models.ForeignKey('ogrenciler.Students.studentName', on_delete=models.CASCADE, related_name='readerName', verbose_name='Okuyan Kişi')
dateOfRead = models.DateField(verbose_name='Okuma Tarihi')
class Meta:
verbose_name = 'Okuma Günlüğü'
Next, you can use ReadList.book.pageCount in your views or in your template.
EDIT
If you want to store the value of book.pageCountas a separate value in your your ReadList object, you can launch a signal after each ReadList creation:
#receiver(post_save, sender=ReadList)
def get_pageCount(sender, instance, **kwargs):
instance.pageCount = instance.book.pageCount
instance.save
I am a beginner in django. Following is my Attendance Management App.
This is my models.py.
from django.db import models
class Subject(models.Model):
subject_name = models.CharField(max_length=20)
#attendance = models.ForeignKey(Attendance, on_delete =
models.DO_NOTHING)
attendance = models.IntegerField(default=0)
def __str__(self):
return self.subject_name
class Section(models.Model):
section_name = models.CharField(max_length=20)
subject = models.ManyToManyField(Subject)
def __str__(self):
return self.section_name
class Student(models.Model):
rollno = models.IntegerField()
name = models.CharField(max_length=20)
section = models.ForeignKey(Section, on_delete = models.DO_NOTHING,
default=0)
def __str__(self):
return str(self.rollno) + self.name
class Teacher(models.Model):
#teacher_name = models.CharField(max_length=20)
section = models.ForeignKey(Section, on_delete=models.CASCADE)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
#section_name = models.CharField(max_length=10)
#subject_name = models.CharField(max_length=30)
def __str__(self):
return self.section.section_name+' '+self.subject.subject_name
class TeacherList(models.Model):
teacher_name = models.CharField(max_length=20)
teacher = models.ManyToManyField(Teacher)
def __str__(self):
return self.teacher_name
The line below is not working in views.py
student = models.Student.objects.get(rollno = sroll)
student.section.subject.get(subject_name = 'java').attendance += 1
student.save()
This view is called from a template when a button is clicked to add attendance of a student.
The attendance in above code is not modified. Please help me out.
You're saving the student, instead of the subject.
student = models.Student.objects.get(rollno = sroll)
subject = student.section.subject.get(subject_name='java')
subject.attendance += 1
subject.save()
Or, better, do the update directly in one go:
student.section.subject.filter(subject_name='java').update(attendance=F('attendance')+1)
and there's no need to save at all.
i want to set diffirent sports to diffirent players
like below. is there anyway to do this?
Example Model :
class Player(models.Model):
id = models.AutoField(primary_key=True)
sportType = models.CharField(max_length=15)
sportObj = generic.GenericForeignKey('content_type')
class Icehockey(models.Model):
id = models.AutoField(primary_key=True)
stick_brand = models.CharField(max_length=50)
skate_number = models.IntegerField()
class Basketball(models.Model):
id = models.AutoField(primary_key=True)
ball_brand = models.CharField(max_length=50)
uniform_color= models.CharField(max_length=10)
class Football(models.Model):
id = models.AutoField(primary_key=True)
shoeNumber = models.IntegerField()
uniform_size = models.CharField(max_length=10)
Example Usage:
player1 = Player.objects.get(id=1).sportObj // returns <Icehockey object>
player2 = Player.objects.get(id=2).sportObj // returns <Basketball object>
player3 = Player.objects.get(id=3).sportObj // returns <Football object>
player4 = Player.objects.get(id=4).sportObj // returns <Football object>
edit :
there is a document on Django Website about How content types works if anyone needs it.
The example you have provided with looks OK to me, I have modified the models a bit to make them usable.
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class Player(models.Model):
SPORT_CHOICES = (
('I', 'Icehockey'),
('B', 'Basketball'),
('F', 'Football'),
)
sportType = models.CharField(max_length=15,choices=SPORT_CHOICES)
sportObj = GenericForeignKey('content_type', 'object_id')
object_id = models.PositiveIntegerField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
class Icehockey(models.Model):
stick_brand = models.CharField(max_length=50)
skate_number = models.IntegerField()
class Basketball(models.Model):
ball_brand = models.CharField(max_length=50)
uniform_color= models.CharField(max_length=10)
class Football(models.Model):
shoeNumber = models.IntegerField()
uniform_size = models.CharField(max_length=10)