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.
Related
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.
I am a beginner in Django. I am building a data model for a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It's table should include:
a. Brand – details on brand, such as, name, origin, manufacturing since, etc
b. Model – details on model, such as, model name, launch date, platform, etc
c. Review – review article on the mobile phone and date published, etc
d. Many-to-many relationship between Review and Model.
Here are my codes in models.py:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brandName = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturingSince = models.CharField(max_length=50, default='null')
def __str__(self):
return self.brandName
class PhoneModel(models.Model):
modelName = models.CharField(max_length=100)
launchDate = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
def __str__(self):
return self.modelName
class Review(models.Model):
model_name_many_to_many = models.ManyToManyField(PhoneModel)
reviewArticle = models.CharField(max_length=1000)
datePublished = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, default='null')
def __str__(self):
return self.reviewArticle
Are my codes correct? Am I in the right direction?
Don't use camelCase in model fields. Use snake_case. Second thing is, when you want field to be default 'null', just use null=True, blank=True(optional value).
I've also provided related_name to your ManyToManyField, so you can use PhoneModelInstance.reviews.all() to get your all reviews for this specific Phone model. For large fields containing text, use TextField.
Edit
I've also added foreign key in PhoneModel which points to the Brand.
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brand_name = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturing_since = models.TextField(null=True, blank=True)
def __str__(self):
return self.brand_name
class PhoneModel(models.Model):
brand_fk = models.ForeignKey(Brand)
model_name = models.CharField(max_length=100)
launch_date = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
def __str__(self):
return self.model_name
class Review(models.Model):
phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
review_article = models.TextField()
date_published = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.review_article
I'm trying to add a data using "Array Model Field"(djongo) as shown Djongo Documentation(Array Model Field) or
from djongo import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
class Meta:
abstract = True
class MetaData(models.Model):
pub_date = models.DateField()
mod_date = models.DateField()
n_pingbacks = models.IntegerField()
rating = models.IntegerField()
class Meta:
abstract = True
class Author(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()
class Meta:
abstract = True
def __str__(self):
return self.name
class Entry(models.Model):
blog = models.EmbeddedModelField(
model_container=Blog,
)
meta_data = models.EmbeddedModelField(
model_container=MetaData,
)
headline = models.CharField(max_length=255)
body_text = models.TextField()
authors = models.ArrayModelField(
model_container=Author,
)
n_comments = models.IntegerField()
def __str__(self):
return self.headline
Into admin.py I added for registration of model in admin panel
from django.contrib import admin
from .models import Entry
admin.site.register(Entry)
And when I try to add a data via http://localhost:8000/admin/ I have a MigrationError...
Where is my mistake? And what am I not understanding?
You should use models.ObjectIdField() on all models to avoid calling django migrations.
Example:
class Author(models.Model):
_id = models.ObjectIdField()
name = models.CharField(max_length=200)
email = models.EmailField()
class Meta:
abstract = True
def __str__(self):
return self.name
See more in Djongo Docs
I'm a stupid. Sry. I didn't 'makemigration' after update a model.
And so here's what I did to make it work:
1. After update a model I did 'python manage.py makemigrations' and that power on.
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)
I need two Django models: first with Users, second with Projects.
Between them I need many-to-many relationship with an additional field(s).
How to make the below code working?
from django.db import models
class User(models.Model):
name = models.CharField('Name', max_length=50)
projects = models.ManyToManyField(Project, through='UserProjects')
def __str__(self):
return self.name
class Project(models.Model):
name = models.CharField('Name', max_length=50)
users = models.ManyToManyField(User, through='UserProjects')
def __str__(self):
return self.name
class UserProjects(models.Model):
user = models.ForeignKey(User)
project = models.ForeignKey(Project)
is_active = models.BooleanField('Active')
At the end User.projects should return Projects for specified User
and in the same way Project.users should return Users for specified Project.
There's no need to put the m2m field on both sides
Jussi pick one, and Django will automatically create a reverse relationship for the other direction.
from django.db import models
class User(models.Model):
name = models.CharField('Name', max_length=50)
def __str__(self):
return self.name
class Project(models.Model):
name = models.CharField('Name', max_length=50)
users = models.ManyToManyField(User, through='UserProjects', related_name='projects')
def __str__(self):
return self.name
class UserProjects(models.Model):
user = models.ForeignKey(User)
project = models.ForeignKey(Project)
is_active = models.BooleanField('Active')
Here is the simplest solution in my opinion:
from django.db import models
class User(models.Model):
name = models.CharField('Name', max_length=50)
class Project(models.Model):
name = models.CharField('Name', max_length=50)
class UserProjects(models.Model):
user = models.ForeignKey(User, related_name='projects')
project = models.ForeignKey(Project, related_name='users')
is_active = models.BooleanField('Active')
In above User.projects returns Projects for specified User and also Project.users returns Users for specified Project.