My model's ER diagram in here
This is part of my models.py.
class Company(models.Model):
user = models.OneToOneField(User)
company_id = models.AutoField(primary_key=True)
...
class Store(models.Model):
store_id = models.AutoField(primary_key=True)
store_company = models.ForeignKey('Company', related_name='storecompany')
store_city = models.ForeignKey('City', related_name='cities', to_field='city_name')
...
class Discount(models.Model):
discount_id = models.AutoField(primary_key=True)
discount_category = models.ManyToManyField(Category, related_name="discountcategory")
discount_store = models.ManyToManyField(Store, related_name="discountstores")
...
class City(models.Model):
city_name = models.CharField(primary_key=True, max_length=25)
class Category(models.Model):
category_id = models.AutoField(primary_key=True)
category_name = models.CharField(max_length=50)
I want to filter discounts with their city. All discounts have a city. For example I received some city name, "bursa" in "city" variable. And I want to filter all discounts in "bursa" city. Maybe my model isn't right but I don't know.
I tried a lot of filter but I couldn't.
First, in your class Store, the related_name is not "correct", it should be something like "stores" not "cities" because related_name attribute specifies the name of the reverse relation from the City model back to your model.
Less assume that you changed it.
class Store(models.Model):
store_id = models.AutoField(primary_key=True)
store_company = models.ForeignKey('Company', related_name='storecompany')
store_city = models.ForeignKey('City', related_name='stores', to_field='city_name')
Then, given a city name
your_city = City.objects.filter(city_name='city_name')[0]
stores = your_city.stores.all()
discounts = [store.discountstores.all() for store in stores]
Always start from the model you actually want to get. If you want Discounts, query that model, using the double underscore syntax to traverse relationships.
Discount.objects.filter(discount_store__store_city__city_name="bursa")
Related
I am getting errors while I am building the following database. Idea is that you create a Team object. Create Student Objects and link them to Teams. And then give the Students points through PointEntry objects. I want to relate the team given to each Student object in each PointEntry Object. But for some reason, Django gives the error:
score_board.Student: (fields.E336) The model is used as an intermediate model by 'score_board.PointEntry.team', but it does not have a foreign key to 'PointEntry' or 'Team'.
Modeladmin Class
class StudentAdmin(admin.ModelAdmin):
list_display = ['name', 'team']
list_filter = ['team']
class PointEntryAdmin(admin.ModelAdmin):
list_display = ['student', 'points']
list_filter = ['student']
Below are the models
class Team(models.Model):
# Team/group model
name = models.CharField(max_length=64)
class Student(models.Model):
# Student model
name = models.CharField(max_length=64)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
def __str__(self):
return f"{self.name}"
class PointEntry(models.Model):
# Point entry's made by users appointed to a student in a group
student = models.OneToOneField(Student, on_delete=models.CASCADE)
points = models.IntegerField()
team = models.ManyToManyField(Team, through='Student')
Your through model needs a ForeignKey to both models. Since the model that defines the ManyToManyField is defined lower, you can not reference to the class. But in Django, you can also use a string literal:
class Student(models.Model):
name = models.CharField(max_length=64)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
pointentry = models.ForeignKey('PointEntry', on_delete=models.CASCADE)
def __str__(self):
return f'{self.name}'
class PointEntry(models.Model):
# Point entry's made by users appointed to a student in a group
student = models.OneToOneField(Student, on_delete=models.CASCADE)
points = models.IntegerField()
team = models.ManyToManyField(Team, through='Student')
Django will then replace the string with a reference to the class.
class Team(models.Model):
# Team/group model
name = models.CharField(max_length=64)
student = models. models.ManyToManyField(Student,through='PointEntry ')
class Student(models.Model):
# Student model
name = models.CharField(max_length=64)
team = models. models.ManyToManyField(Team,through='PointEntry')
def __str__(self):
return f"{self.name}"
class PointEntry(models.Model):
# Point entry's made by users appointed to a student in a group
student = models. ForeignKey(Student,on_delete=models.CASCADE)
team = models. ForeignKey(Team, on_delete=models.CASCADE)
points = models.IntegerField()
I think a model like this might work for what you’re trying to achieve.
I have a product model with name, description, currency, price, vendor and image fields, and I'm trying to implement ordering items, and I'm having a bit of trouble doing that.
Basically, what I want is to be able to access an Orders model in the admin and add an order number, customer name (I have already implemented these two), and some products with each product having a quantity.
# models.py
from django.db import models
class Vendor(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Product(models.Model):
currencies = [
('$', "US Dollars ($)"),
]
name = models.CharField(max_length=40)
description = models.TextField()
currency = models.CharField(max_length=5, choices=currencies, default="$")
price = models.DecimalField(max_digits=10, decimal_places=2)
vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE)
image = models.ImageField(default="not_found.jpg")
def __str__(self):
return self.name
class Customer(models.Model):
name = models.CharField(max_length=30)
date_of_birth = models.DateField()
def __str__(self):
return self.name
class Order(models.Model):
order_number = models.CharField(max_length=20)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
My attempts/solutions:
Adding ManyToManyField to Product (No Quantity)
Creating ProductInstance class with fk to product and order (Quantity added but You have to visit 2 different pages in the admin, and you can't see the items in orders page of admin)
Are there any other ways I can implement this or am I stuck with the second solution? It wouldn't be awful to do this but I rather avoid it and have the ability to add items on the orders page
I'm sorry if I sound like a beggar. I'm really not but I can't form nice-sounding sentences
Edit: I found what I needed!
Using the second solution I mentioned, I created a class called ProductInstance, and later renamed it to OrderProduct, made the following fields:
ForeignKey to Products
ForeignKey to Orders
IntegerField for quantity
The order class had the following fields:
CharField for order number
ForeignKey for customer
ManyToMany to product through OrderProduct
Then, I added the following in admin.py:
# admin.py
...
class OrderInlines(admin.TabularInline):
model = OrderProduct
fk_name = "order"
extra = 1
#admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
fields = ('order_number', "customer",)
inlines = (OrderInlines,)
I am trying to create the proper Django model that could fit the following reqs:
Person Class has 1 to many relations with the Address Class
Person Class has many to many relations with the Group Class
Book Class contains the collections of the Persons and the Groups
This is my code:
class Person(models.Model):
first_name = models.CharField(max_length=15)
last_name = models.CharField(max_length=20)
def __str__(self):
return self.first_name+ ' - ' + self.last_name
class Address(models.Model):
person = models.ForeignKey(Person)
address_line = models.CharField(max_length=200)
def __str__(self):
return self.address_line
class Group(models.Model):
group_name = models.CharField(max_length=12)
persons = models.ManyToManyField(Person)
def __str__(self):
return self.group_name
class Book(models.Model):
record_name = models.CharField(max_length=12)
person = models.ForeignKey(Person )
group = models.ForeignKey(Group )
def __str__(self):
return self.record_name
However it's not correct:
1) A Group can now contain multiple Persons but the Persons do not contain any Group.
I am not sure if I should add to the Person class the following code:
groups = models.ManyToManyField(Group)
2) The Book class now contains only 1 record of Person & Group per Book record.
3) When I added the Foreign Keys to the models, I removed
on_delete tag:
person = models.ForeignKey(Person, on_delete=models.CASCADE())
because it does not compile it, asking for some params.
I know how to make all this for C#, but I am a kinda stucked with this simple task in Python/Django.
1) The ManyToMany field should appear only in one of the models, and by looks of things you probably want it in the Person model.
Its important to understand that the data about the ManyToMany field is saved in a differant table. Django only allows this field to be visable through buth models (so basiclly, choose where it is move convinient).
2)By the look of your structure I will suggest you use a ManyToMany field through a different table. here is an example:
class Activity(models.Model):
name = models.CharField(max_length=140)
description = models.TextField(blank=True, null=True)
class Route(models.Model):
title = models.CharField(max_length=140)
description = models.TextField()
activities_meta = models.ManyToManyField(Activity, through = 'RouteOrdering')
class RouteOrdering(models.Model):
route = models.ForeignKey(Route, on_delete=models.CASCADE)
activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name='activita')
day = models.IntegerField()
order = models.IntegerField(default=0)
that way the data is binded to the ManyToMany field
Can anyone help me fetch data from this model structure? because i have a hard time doin this for hours now.
First I would like to get all distinct SubSpecialization from all Doctor which has a given Specialization.title
Secondly I would like to get all Doctor which has a specific Specialization.title and has no SubSpecialization.
Here is the Doctor model
class Doctor(models.Model):
name = models.CharField(max_length=50)
room_no = models.IntegerField()
floor_no = models.IntegerField()
contact_no = models.CharField(max_length=50, blank=True, null=True)
notes = models.CharField(max_length=70, blank=True, null=True)
This is the model Doctor relationship is connected to Specializationand SubSpecialization.
class DoctorSpecialization(models.Model):
doc = models.ForeignKey(Doctor, models.DO_NOTHING)
spec = models.ForeignKey('Specialization', models.DO_NOTHING)
class DoctorSubSpecialization(models.Model):
doc = models.ForeignKey(Doctor, models.DO_NOTHING)
sub_spec = models.ForeignKey('SubSpecialization', models.DO_NOTHING)
This is where i would make a criteria.
class Specialization(models.Model):
title = models.CharField(unique=True, max_length=45)
point = models.IntegerField()
class SubSpecialization(models.Model):
title = models.CharField(max_length=100)
There is no direct relationship between the Specialization and SubSpecialization please help.
Firstly, your specialization and subspecialization are both many-to-many relationships with Doctor. You should declare that explicitly, and drop those intervening models unless you need to store other information on them.
class Doctor(models.Model):
...
specializations = models.ManyToManyField('Specialization')
subspecializations = models.ManyToManyField('SubSpecialization')
Now you can query for all the subspecializations for doctors who have a specific specialization:
SubSpecialization.objects.filter(doctor__specialization__title='My Specialization')
Your second query doesn't make sense given the fact there is no relationship between specialization and subspecialization, you'll need to clarify what you mean by "no subspecialization in a specific specialization".
Edit
To find doctors who have a specific Specialization and then no subspecializations at all:
Doctor.objects.filter(specialization__name="My Specialization",
subspecialization=None)
I have two models User and Company
class Company(models.Model):
name = models.CharField max_length=50)
class User(models.Model):
name = models.CharField( max_length=40)
following = models.ManyToManyField(Company)
I want to get all the company which has some users are following them.
Something like
Company.objects.filter(has_following = True)
How can i do it ?
You can use the related_name when declaring a M2M relationship:
class User(models.Model):
name = models.CharField(max_length=40)
following = models.ManyToManyField(Company, related_name='followers')
Then, you can query it using:
>>> Company.objects.exclude(followers=None)