I have tree models related to each others as follow :
The first class has basic informations about the project.
class Project(models.Model):
customer = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete = models.CASCADE,)
title = models.CharField(max_length=200)
pub_date = models.DateTimeField(default=timezone.now)
The second class is used to register the categories related to every project.
class ProjectCategory(models.Model):
project = models.ForeignKey(
Project,
on_delete = models.CASCADE)
projectCategory = models.ForeignKey(
Category,
on_delete=models.CASCADE)
The last model indicates the locations of the project.
class ProjectLocation(models.Model):
project = models.ForeignKey(
Project,
on_delete = models.CASCADE)
projectLocation = models.ForeignKey(
Location,
on_delete=models.CASCADE)
I was trying to render in a template a list of projects.
I want to show the informations (Categories and Locations) related to each project.
How can achieve that ?
Using the query Project.objects.all() doesn't allow me to access the fields "projectLocation" and "projectCategory".
Add a related_name to your foriegn key fields, and you can access them by this name.
For example ProjectCategory:
class ProjectCategory(models.Model):
project = models.ForeignKey(Project, related_name='categories')
so now you can do:
project.categories.all()
Related
Existed models:
class OrderDocument(models.Model):
name = models.CharField(max_length=100)
file = models.FileField(upload_to=get_document_name)
order_group = models.ForeignKey(OrderGroup, on_delete=models.CASCADE, null=True, related_name='documents')
class Order(models.Model):
name = models.CharField(max_length=100)
order_group = models.ForeignKey(OrderGroup, on_delete=models.CASCADE, null=True, related_name='orders')
class OrderGroup(models.Model):
name = models.CharField(max_length=100)
I want to rewrite it for add ability to add OrderDocuments and choose with what table (Order or OrderGroup) it will related. Which way will the best in this case to implement it?
It can be more than 2 relations in future.
I don't want using m2m in Order and OrderGroup
Order can be without OrderGroup
We have defined two apps: Manin_matrix and SW_matrix.
We want the field name (project_name) present in class GENERAL_t of models.py file inside Main_matrix app to be inside the models.py file of SW_matrix app.
Basically, project_name_work field in class EDVT of SW_matrix models.py should be the same as project_name of Main_matrix app.
We want this so that in a database for EDVT table we will get the same project id along with the project name.
Main_matrix/models.py
class GENERAL_t(models.Model):
project_name = models.CharField(
blank=True,
null=True,
max_length=40,
verbose_name='Project_Name'
)
platform = models.CharField(
blank=True,
null=True,
max_length=40,
verbose_name='Platform SW'
)
SW_matrix/models.py
class EDVT(models.Model):
project_rel=models.ForeignKey(
GENERAL_t,
null=True,
on_delete=models.SET_NULL,
verbose_name="Choose Project"
)
project_name_work = models.ForeignKey(
GENERAL_t.project_name,
null=True,
verbose_name='Project_Name'
)
You don't need to do that, and a FK won't allow that. The FK field is just the ID of a row in another table, nothing more complex than that really.
When working with ForeignKey links like this it's a good idea to use strings so that you don't have to import the related model. The format of the string is '<appname.ModelName>
For example, I link an object to a (django) content type like this;
source_content_type = models.ForeignKey(
verbose_name=_('source content type'),
to='contenttypes.ContentType',
on_delete=models.CASCADE
)
So to link your EDVT model to a GENERAL_t you'd do;
class EDVT(models.Model):
general_t = models.ForeignKey(
to='Manin_matrix.GENERAL_t',
null=True,
verbose_name='general t'
)
Then if EDVT needs to be able to return a project_name you could do it as a property.
class EDVT(models.Model):
project_rel = models.ForeignKey(
to='Manin_matrix.GENERAL_t',
null=True,
verbose_name='Project_Name'
)
#property
def project_name(self):
return self.project_rel.project_name
Then you can access it either by EDVT.objects.first().project_name or if you didn't implement the property you can do EDVT.objects.first().general_t.project_name (or any other field on that model)
I have this models in my Django ganalytics app:
class Article(models.Model):
id = models.IntegerField(unique=True, primary_key=True)
article_title = models.CharField(max_length=250)
article_url = models.URLField(max_length=250)
article_pub_date = models.DateField()
class Company(models.Model):
company_name = models.CharField(max_length=250)
class Author(models.Model):
author_sf_id = models.CharField(max_length=20, null=True)
author_name = models.CharField(max_length=250)
class AuthorArticleCompany(models.Model):
author = models.ForeignKey(Author,
to_field="id",
on_delete=models.CASCADE,
related_name='authorarticle_author_id')
company = models.ForeignKey(Company,
to_field="id",
on_delete=models.CASCADE,
related_name='authorarticle_company_id')
article = models.ForeignKey(Article,
to_field="id",
on_delete=models.CASCADE,
related_name='authorarticle_article_id')
class Ganalytics(models.Model):
article = models.ForeignKey(Article,
on_delete=models.CASCADE,
related_name='ganalytics_author_id')
totalview = models.IntegerField()
totalinteractions = models.IntegerField()
class Unsubscribers(models.Model):
email = models.EmailField()
reasonwhy = models.CharField(max_length=90)
I am running pandas to_sql to upload the database:
authorarticlecompanydf.to_sql("ganalytics_authorarticlecompany", con=engine, if_exists="append", index=False)
articledf.to_sql("ganalytics_article",con=engine,if_exists="replace",index=False)
company_name.to_sql("ganalytics_company",con=engine,if_exists="replace",index=False)
authordf.to_sql("ganalytics_author", con=engine,if_exists="replace", index=False)
I am getting this error message:
DETAIL: constraint ganalytics_ganalytic_article_id_d37f2464_fk_ganalytic on table ganalytics_ganalytics depends on table ganalytics_article
constraint ganalytics_authorart_article_id_7f4ff374_fk_ganalytic on table ganalytics_authorarticlecompany depends on table ganalytics_article
HINT: Use DROP ... CASCADE to drop the dependent objects too.
[SQL:
DROP TABLE ganalytics_article]
I have tried to change the on_delete field to different values but it wont help.
What am I doing wrong?
What is the command you are running to get the error? The bottom line is Ganalytics depends on Article via the FK between them. By dropping Article first you are breaking that dependency. You either need to DROP Ganalytics first and then Article or follow the hint DROP ... CASCADE. Though be aware that will DROP Ganalytics also.
UPDATE
Another option would be to drop the FK between the two tables. Then you would not have the dependency issue.
In the past, I think there was a model atrtibute named unique_for to define a foreignKey but I can't find it anymore.
Suppose a model named Recommendation. A User can recommend many websites but only one by domain. So, I wanted to set a unique_for('user', 'recommendation.domain') or something like like this.
What's the current way to do it ?
Recommendation Model:
class Recommendation(models.Model):
is_recommended = models.BooleanField(default=True)
what = models.ForeignKey('Website', on_delete=models.CASCADE)
who = models.OneToOneField(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
why = models.CharField(max_length=255, null=True, blank=True)
when = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-when"]
User Model is the Django built in.
Thanks
I've found my answser.
The attribute is unique_together and not unique_for
I want to link two models using foreignKey, The problem is when i try to do that, one model does not get foreignKey value for the next model in the database table.
The aim is for user to fill information on the first page (have its own model and template) then click next (fill more info in the next page having its own model and template) then click next for the same logic. then when other users view this post it must show all content from different models in one page. here is my code.
1st model
class Map(models.Model):
user = models.ForeignKey(User, default=None, blank=True, null=True, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
position = GeopositionField()
HAVING ITS OWN TEMPLATE
2nd Model
class Post(models.Model):
parent = models.ForeignKey("self", default=None, blank=True, null=True, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, on_delete=models.CASCADE)
title = models.CharField(max_length=50)
content = models.TextField()
map = models.ForeignKey(Map, related_name='mapkey', default=None, blank=True, null=True, on_delete=models.CASCADE)
HAVING ITS OWN TEMPLATE BUT also has serializer method(API) below:
class PostModelSerializer(serializers.ModelSerializer):
user = UserDisplaySerializer(read_only=True)
parent = ParentPostModelSerializer()
map = serializers.SerializerMethodField()
class Meta:
start_date = forms.DateField(widget = forms.SelectDateWidget())
end_date = forms.DateField(widget = forms.SelectDateWidget())
model = Post
fields = [
'id',
'user',
'title',
'content'
'image',
'map',
]
Please focus only on the map field as its isolated in the above codes
everything works perfectly, but the foreignKey. also i didnt see the need to include all the code here but snippets.
i have been struggling with this for days now. do i need to write an api for 1st model also? for views i used class based views.
the database table for model 2, on the map field it shows null all the time.
I have i have provided enough information.Thanks