Greetings, I have these 2 models:
from django.db import models
class Office(models.Model):
name = models.CharField(max_length=30)
person = models.CharField(max_length=30)
phone = models.CharField(max_length=20)
fax = models.CharField(max_length=20)
address = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Province(models.Model):
numberPlate = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
content = models.TextField()
office = models.ForeignKey(Office)
def __unicode__(self):
return self.name
I want to be able to select several Offices for Provinces, which is a one to many model. Here is my admin.py:
from harita.haritaapp.models import Province, Office
from django.contrib import admin
class ProvinceCreator(admin.ModelAdmin):
list_display = ['name', 'numberPlate','content','office']
class OfficeCreator(admin.ModelAdmin):
list_display = ['name','person','phone','fax','address']
admin.site.register(Province, ProvinceCreator)
admin.site.register(Office, OfficeCreator)
Right now, I am able to select one Office per Province at the admin panel while creating a new Province but I want to be able to select more than one. How can I achieve this?
Regards
I'm not sure if I'm misunderstanding you, but your models currently say "an office can be associated with many provinces, but each province may only have one office". This contradicts what you want. Use a ManyToMany field instead:
class Province(models.Model):
numberPlate = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
content = models.TextField()
office = models.ManyToManyField(Office)
def __unicode__(self):
return self.name
Related
I need to have user inputing his address by first select country, then city, then district, and then sub-district. How do I best implement this functionality in django Form? The models are similar to this:
Class Country(models.Model):
name = models.CharField(max_length=30)
Class City(models.Model):
name = models.CharField(max_length=30)
country = models.ForeignKey(Country)
Class District(models.Model):
name = models.CharField(max_length=30)
city = models.ForeignKey(City)
Class Subdistrict(models.Model):
name = models.CharField(max_length=30)
district = models.ForeignKey(District)
You can use Filtering results based on the value of other fields in the form from django-autocomplete-light
I have a series of related models. Country -> League -> Team -> Player. The model works fine relating country to league and league to team, but the team id is different as teams play in more than one competition. To deal with this I've added a ref column with an id for each team. I would like to use this ref column as the Foreign Key in my player model but I'm getting errors when I try to parse the data to the Postgres database.
I've tried using to_field and unique=True but still end up with an error. I've taken a look around but haven't found a solution yet.
Here is my models code:
from django.conf import settings
from django.db import models
from django.utils import timezone
import datetime
class Country(models.Model):
objects = models.Manager()
name = models.CharField(max_length=50,default="TBA")
id = models.IntegerField(primary_key=True,default=0)
def __str__(self):
return self.name
def __unicode__(self):
return u'%s' % self.name
class League(models.Model):
objects = models.Manager()
name = models.CharField(max_length=100,default="TBA")
id = models.IntegerField(primary_key=True,default=0)
country = models.ForeignKey(Country,on_delete=models.CASCADE)
def __str__(self):
return self.name
def __unicode__(self):
return u'%s' % self.name
class Team(models.Model):
objects = models.Manager()
name = models.CharField(max_length=100,default="TBA")
id = models.IntegerField(primary_key=True,default=0)
league = models.ForeignKey(League,on_delete=models.CASCADE)
ref = models.IntegerField(default=0)
def __str__(self):
return self.name
def __unicode__(self):
return u'%s' % self.name
class Player(models.Model):
objects = models.Manager()
name = models.CharField(max_length=64)
id = models.IntegerField(primary_key=True)
first_name = models.CharField(max_length=64,default="Unknown")
last_name = models.CharField(max_length=64,default="Unknown")
nationality = models.CharField(max_length=64,default="Unknown")
date_of_birth = models.DateField(default = datetime.date.today)
position = models.CharField(max_length=64, default="Unknown")
team_ref =models.ForeignKey(Team,to_field="ref",on_delete=models.CASCADE)
def __str__(self):
return self.name
IMHO, I think you model design is bit wrong. You should make Team to League relation as ManyToMany Field. So that, a Team can be assigned to multiple Leagues. If you want to maintain different Squads for different Tournaments, then you should create a new Model Named Squads and use it as through, and make a many to many relation to that Squads Model from Player. For example:
class Team(models.Model):
# other fields
league = models.ManyToManyField(League, through="Squad")
class Squad(models.Model):
team = models.ForeignKey(Team)
league = models.ForeignKey(League)
class Player(models.Model):
squad = models.ManyToManyField(Squad)
I'm trying to get a PurchaseOrder that can be added indefinitely many times. Maybe this is easier than I am thinking, but here is my problem in this imagine:
I would like it to where instead of adding another VendorProfile, it'll add another PurchaseOrder. My end goal is to be able to add 1, 2, 20, etc. PurchaseOrder from the same add screen. Not to be able to add a PurchaseOrder, and then a VendorProfile.
Here's some code: In models.py
class PurchaseOrder(models.Model):
product = models.CharField(max_length=256)
dollar_amount = models.FloatField()
item_number = models.AutoField(primary_key=True)
vendor = models.ForeignKey('VendorProfile')
class VendorProfile(models.Model):
name = models.CharField(max_length=256)
address = models.CharField(max_length=512)
city = models.CharField(max_length=256)
In admin.py
class ProductInline(admin.StackedInline):
model = VendorProfile
extra = 3
class PurchaseOrderAdmin(admin.ModelAdmin):
#...
inlines = [ProductInline]
If I understand you correctly, you whant associate many PurchaseOrder's to one VerndorProfile. In such a case it would be better to use ManyToManyField.
Example:
models.py:
class PurchaseOrder(models.Model):
product = models.CharField(max_length=256)
dollar_amount = models.FloatField()
item_number = models.AutoField(primary_key=True)
def __unicode__(self):
return u'{} {}'.format(self.product, self.dollar_amount)
class VendorProfile(models.Model):
name = models.CharField(max_length=256)
address = models.CharField(max_length=512)
city = models.CharField(max_length=256)
purchased_orders = models.ManyToManyField('PurchaseOrder')
admin.py
class VendorProfileAdmin(admin.ModelAdmin):
filter_horizontal = ('purchased_orders', )
admin.site.register(VendorProfile, VendorProfileAdmin)
I have 3 inherited classes (Fitters -> Workers -> Staffs) connected with tables in my Database (class names in the plural, but that's not important now).
User can add/edit/remove only Fitters. The Workers and Staffs tables are updated automatically (cascaded).
It works fine: when I add new Fitter, all changes come to all tables in database. But when I want to edit any Fitter via Django admin tool, I go to edit Fitter page and I see incorrectly filled fields.
For example:
In Staffs table I have "John Smith" with id=41
In Workers table I have the record with id=21 and ForeignKey=41 (to John Smith)
In Fitters table I have the record with id=5 and ForeignKey=21 (to record in Workers table)
When I go to edit Fitter "John Smith" page, I see all fields filled by "Kevin Thomas" (id=21 in Staffs table!).
So, Django misses the Workers table and goes directly to the Staffs table.
How can I fix it?
Here is my draft code:
class Staffs(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=135, blank=True)
surname = models.CharField(max_length=135, blank=True)
def __unicode__(self):
return self.name + " " + self.surname
class Meta:
db_table = u'staffs'
class Workers(Staffs):
idWorker = models.AutoField(primary_key=True, db_column='id')
staffs_idstaff = models.OneToOneField('Staffs', db_column='Staffs_idstaff', parent_link=True)
brigades_idbrigade = models.ForeignKey('Brigades', db_column='Brigades_idBrigade')
def __unicode__(self):
return self.staffs_idstaff.name + " " + self.staffs_idstaff.surname
class Meta:
db_table = u'workers'
class Fitters(Workers):
idFitter = models.AutoField(primary_key=True, db_column='id')
qualification = models.CharField(max_length=135, blank=True)
workers_idworker = models.OneToOneField('Workers', db_column='Workers_idWorker', parent_link=True)
def __unicode__(self):
staff = self.workers_idworker.staffs_idstaff
return staff.name + " " + staff.surname
class Meta:
db_table = u'fitters'
EDIT1:
I tried to change my code like this:
class Staffs(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=135, blank=True)
surname = models.CharField(max_length=135, blank=True)
class Meta:
db_table = u'staffs'
class Workers(Staffs):
idWorker = models.AutoField(primary_key=True)
brigades_idbrigade = models.ForeignKey('Brigades')
class Meta:
db_table = u'workers'
class Fitters(Workers):
idFitter = models.AutoField(primary_key=True)
qualification = models.CharField(max_length=135, blank=True)
class Meta:
db_table = u'fitters'
It's pretty simple now. I synced my database, but I have the absolutely same problem!
EDIT2:
Part of my admin.py file:
from django.contrib import admin
from appclient.models import *
admin.site.register(Fitters)
admin.site.register(Staffs)
admin.site.register(Workers)
...
SOLUTION:
Solution is I don't need use my own id's and ForeignKey's for each model. Djando automatically creates special field for each model and uses it as an id (PrimaryKey) and for link to the parent tables (ForeignKey).
Here is solution:
class Staffs(models.Model):
name = models.CharField(max_length=135, blank=True)
surname = models.CharField(max_length=135, blank=True)
class Meta:
db_table = u'staffs'
class Workers(Staffs):
brigades_idbrigade = models.ForeignKey('Brigades')
class Meta:
db_table = u'workers'
class Fitters(Workers):
qualification = models.CharField(max_length=135, blank=True)
class Meta:
db_table = u'fitters'
Thanks to everyone who helped me.
This does seem somewhat strange. However, as far as I understand, Django will automatically setup the required one-to-one mappings between parents and children, when using multi-table inheritance. As you have also set these up manually, it might very well be that some kind of inconsistency is introduced due this.
If you take a look directly in the database, are the two different one-to-one relations consistent?
What happens if you remove the explicit one-to-one fields from your models?
Experts!
Having the following models.py
class Country(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Countries Uploaded'
class Users(models.Model):
name = models.CharField(max_length=50)
cUsers = models.ForeignKey(Country)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Users on a country'
class GoalsinCountry(models.Model):
Country = models.ForeignKey(VideoTopic)
name = models.CharField(max_length=50)
descr = models.TextField(blank=True, null=True)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Goals Topic'
I would like to filter out the users that belongs to a particular country and not all see all users when choosing a country on the combobox, and be able to save this information to a sqlite3 db.
if I add the following code below Country = Models..
gUser = models.ForeignKey(Users)
Using the Django admin interface, will show all users, not filtering users based on the country they are.. Would this be possible to do with Django + Something else? is there any working example/Tutorial - like the northwind MS Tutorial?
Thank you