this is my models.py
from django.db import models
# Create your models here.
class Leagues(models.Model):
LeagueName = models.CharField(max_length=200)
class Team(models.Model):
TeamName = models.CharField(max_length=200)
class LeagueTable(models.Model):
league = models.ForeignKey(Leagues)
team = models.CharField(max_length=200)
matches_played = models.IntegerField()
matches_won = models.IntegerField()
matches_drawn = models.IntegerField()
matches_lost = models.IntegerField()
points = models.IntegerField()
class FixtureTable(models.Model):
league = models.ForeignKey(Leagues)
fixture_date = models.DateField('Fixture Date')
team_one = models.CharField(max_length=200)
team_one_score = models.IntegerField()
team_two = models.CharField(max_length=200)
team_two_score = models.IntegerField()
in the "class FixtureTable", i want team_one and team_two to be linked to two differnt teams in "class Team" models. how to create multiple relations, or is it possible.
PS: this is purely a noob, with a little experience in programming, but no experience with either python or databases.
thankyou.
You can create as many ForeignKeys as you like to the same model. I suspect what's tripping you up is Django giving you an error saying that you need to specify a related name.
By default, Django creates an attribute on the opposite model of the form <model>_set. So in the following scenario:
class FixtureTable(models.Model):
team_one = models.ForeignKey(Team)
Django would add a related manager to Team as fixturetable_set. If you then did:
class FixtureTable(models.Model):
team_one = models.ForeignKey(Team)
team_two = models.ForeignKey(Team)
Django would attempt to add the same attribute twice and obviously fail. The fix is to specify a related_name, so each can have a unique related manager:
class FixtureTable(models.Model):
team_one = models.ForeignKey(Team, related_name='team_one_fixturetables')
team_two = models.ForeignKey(Team, related_name='team_two_fixturetables')
Then, everything will work fine. You can specify whatever you like for related_name as long as it's unique for the model.
Related
I have a model for a product:
class Product(models.Model):
name = models.CharField(verbose_name=_("Name"), max_length=120)
slug = AutoSlugField(populate_from="name", verbose_name=_("Slug"), always_update=False, unique=True)
I want to have a separate model ProductFields:
class ProductFields(models.Model):
field_name = models.CharField()
field_type = models.CharField()
field_verbose_name = models.CharField()
field_max_length = models.IntegerField()
filed_null = models.CharField()
field_blank = models.BooleanField()
field_default = models.CharField()
...
So the idea is whenever I add new ProductField I want Product model to migrate that added field to its database.
For Example:
ProductFields.objects.create(field_name='description', field_type='CharField', field_verbose_name='Description', field_max_length=255, filed_null=True, filed_blank=True)
This should transform Product modal to:
class Product(models.Model):
name = models.CharField(verbose_name=_("Name"), max_length=120)
slug = AutoSlugField(populate_from="name", verbose_name=_("Slug"), always_update=False, unique=True)
description = models.CharField(verbose_name="Description", max_length= 255, null=True, blank=True)
Please let me know if you have any idea how this can be done?
If you're looking for a way to create a dynamic model you can look into these suggestions.
HStoreField using django-hstore : https://django-hstore.readthedocs.io/en/latest/
JSONField: JSONField is similar to HStoreField, and may perform better with large dictionaries. It also supports types other than strings, such as integers, booleans and nested dictionaries.https://django-pgfields.readthedocs.io/en/latest/fields.html#json-field
Or you can use a NoSQL database (Django MangoDB or another adaptation)
The idea is super simple. This is specific to my project, I want to add data to 2 objects of the same model on one Django admin page and have one save button.
My class:
class Data(models.Model):
issuer = models.ForeignKey(Issuers, on_delete=models.CASCADE)
issuer_field = models.ForeignKey(Fields, on_delete=models.CASCADE, null=True)
data_year = models.PositiveSmallIntegerField()
long_term_ar = models.IntegerField()
section_1 = models.IntegerField()
short_term_ar = models.IntegerField()
short_term_investments = models.IntegerField()
cash = models.IntegerField()
To illustrate:I want to have 2 of those on the same page
I am new to Django, and it will be super helpful if you will help me implement this idea
Take a look on "Inlinemodeladmin objects": https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#inlinemodeladmin-objects
You will be able to add more than one record at the same time:
Try this approach. I am still learning Django too. However, I believe that you dont need to specify the save instance since it is already built in django.
models.py
class Data(models.Model):
issuer = models.ForeignKey(Issuers, on_delete=models.CASCADE)
issuer_field = models.ForeignKey(Fields, on_delete=models.CASCADE, null=True)
data_year = models.PositiveSmallIntegerField()
long_term_ar = models.IntegerField()
section_1 = models.IntegerField()
short_term_ar = models.IntegerField()
short_term_investments = models.IntegerField()
cash = models.IntegerField()
admin.py
from django.contrib import admin
from .models import Data
class DataAdmin(admin.ModelAdmin):
list_display = ('issuer', 'issuer_field')
admin.site.register(Data)
What is the process that you follow to create model in Django? Thanks.
The most important part of a model – and the only required part of a model – is the list of database fields it defines. Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean, save, or delete.
Models.py
from django.db import models
class Musician(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)
class Album(models.Model):
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
release_date = models.DateField()
num_stars = models.IntegerField()
You can start here Documentation
See also Django Girls Models
I am struggling to understand how one-to-many and many-to-many relation works in Django model. My schema looks something like this so far, I am open for suggestions to make it better.
A many-to-many relation between users and team. Also, there will be schedules that belong to a particular user of a team.
This is how my model looks like so far,
class Team(models.Model):
tid = models.AutoField(primary_key=True)
team_name = models.CharField(max_length=30)
manager_name = models.CharField(max_length=30)
class Schedule(models.Model):
sid = models.AutoField(primary_key=True)
user = models.OneToOneField(User)
date = models.DateField()
start_time = models.TimeField()
end_time = models.TimeField()
pay_rate = models.CharField(max_length=30)
location = models.CharField(max_length=50)
class BelongsTo(models.Model):
bid = models.AutoField(primary_key=True)
user = models.OneToOneField(User)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE)
Question: I want to get the information of each user, what are their schedules and which team each schedule belongs to. How would I to do it? I have tried BelongsTo.objects.select_related().all(), but it is not working for me.
Note: I am open for suggestions, if something is wrong with my schema or model or the approach, please let me know.
BelongsTo is seems like utility table.So
BelongsTo.objects.all().values('user', 'team__team_name', 'schedule')
Your schema looks almost right, but I would modify it a little bit. In particular, I will change how Schedule is implemented. Instead of having a sid in the User Belongs To join-table, I would include the user and team in the Schedule table as foreign keys.
This is how the Django models should then look like:
class User(models.Model):
username = models.CharField(max_length = 200)
# put other fields like password etc. here
class Team(models.Model):
team_name = models.CharField(max_length=30)
manager_name = models.CharField(max_length=30)
user = models.ManyToManyField("User")
class Schedule(models.Model):
user = models.ForeignKey("User")
team = models.ForeignKey("Team")
date = models.DateField()
start_time = models.TimeField()
end_time = models.TimeField()
pay_rate = models.CharField(max_length=30)
location = models.CharField(max_length=50)
Note the following:
You don't need to have a primary key field in the models because Django adds a primary key field called pk or id automatically.
Note the absence of the User Belongs To model. Django implements join-tables like User Belongs To automatically when you use a ManyToManyField. See the Django docs on many-to-many relationships.
You also don't need on_delete = models.CASCADE on ForeignKey fields, because this is the default behavior.
To see how to get information about users, teams and schedule from this configuration of models, consult the Django documentation on making db queries. It's quite easy.
Looking for advice on setting up this model.
This job board app has Company, Location, and Job. They should have the following relationships:
A Company can have multiple locations
A Company can have multiple jobs
A Job can have only one Company
A Job can have multiple locations, BUT each Location must be valid for the job's Company
I'd like to create a model that reflects these relationships. I think something like this might work:
class Company(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
class Location(models.Model):
is_primary_location = models.BooleanField()
address = models.CharField(max_length=200)
company = models.ForeignKey(Company)
class Job(models.Model):
title = models.CharField(max_length=200)
company = models.ForeignKey(Company)
location = models.ForeignKey(Location)
But I would really like the "Job has Location(s) through Company" relationship to be enforced. The model doesn't enforce it; I think I'd have to filter the valid Locations when data is displayed, and I'd like to avoid that.
Thanks very much!
Take a look at ForeignKey.limit_choices_to.
This allows you to filter the available choices and is enforced in ModelForm. Since you already have the company foreign key in your Job model, you should be able to use that to filter the choices.
I ended up using https://github.com/digi604/django-smart-selects and wrote the model like this. I don't think limit_choices_to works in this case (according to other SO threads)
from smart_selects.db_fields import ChainedForeignKey
class Company(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
class Location(models.Model):
is_primary_location = models.BooleanField()
address = models.CharField(max_length=200)
company = models.ForeignKey(Company)
class Job(models.Model):
title = models.CharField(max_length=200)
company = models.ForeignKey(Company)
location = ChainedForeignKey(
Location,
chained_field="company",
chained_model_field="company",
show_all=False,
auto_choose=True
)