I am working on a Django project where I need to link one table(model) to each user.
Assume MyTable_1 maps to user_1 and so on.
The primary key for MyTable will be a DateField which contains continuous dates from the time user signed-up.
MyTable_1 for User_1
|-----------|----------|-------------|-----------------|
| Date(PK) | food_ate | game_played | ran_today |
|-----------|----------|-------------|-----------------|
| 10/01/20 | rice | chess | Yes |
|-----------|----------|-------------|-----------------|
| 11/01/20 |sandwhich | tennis | No |
|-----------|----------|-------------|-----------------|
MyTable_2 for User_2
|-----------|----------|-------------|-----------------|
| Date(PK) | food_ate | game_played | ran_today |
|-----------|----------|-------------|-----------------|
| 16/03/19 | pizza | rugby | Yes |
|-----------|----------|-------------|-----------------|
| 17/03/19 | pasta | football | Yes |
|-----------|----------|-------------|-----------------|
And so on for every new user created. User logs in those information in MyTable.
How can I implement this? I am using PostgreSQL and have written custom User Model.
You really don't need seperate tables just seperate rows.
A ForeignKey relation will do the trick, something like this in your models.py:
# user model:
User(models.Model, ...):
first_name = models.CharField(...)
last_name = models.CharField(...)
...
# log model:
Log(models.Model):
user = models.ForeignKey(User, ...)
date = models.DateField(...)
food_ate = models.CharField(...)
game_played = models.CharField(...)
ran_today = models.CharField(...)
class Meta: unique_together = ('user', 'date',)
Then, elsewhere, you can access your users' logs like so:
user = User.objects.get(id='the_user_id')
logs = user.logs.all()
Related
There is a Django filter problem with ManyToManyField that bothers me.
I have a task that I want the creator and selected members of the creator to view. Now I have a problem that the specified member can be viewed normally, but when the creator views it, there will be the same number of duplicate tasks as the specified member. I can't understand this problem, it is not what I expected.
#views
class TaskView(LoginRequiredMixin, View):
def get(self, request):
projecttask_all = ProjectTask.objects.filter(Q(owner=request.user.username) |
Q(task_member=request.user))
print(projecttask_all)
#print results
<QuerySet [<ProjectTask: user1>, <ProjectTask: user1>]>
// My understanding should be like <QuerySet [<ProjectTask: user1>]>, because the owner is not in projecttask_task_member,but it is not.
#model
class ProjectTask(models.Model):
title = models.CharField(max_length=100, verbose_name='title', default='')
owner = models.CharField(max_length=30, verbose_name='owner')
task_member = models.ManyToManyField('UserProfile',related_name='task_member', blank=True, null=True)
#mysql
projecttask
| id | title | owner |
| -- | ----- | ----- |
| 1 | test | user1 |
projecttask_task_member
| id | projecttask_id | userprofile_id |
| -- | -------------- | -------------- |
| 1 | 1 | 8 |
| 2 | 1 | 9 |
I've cloned a Django/Angular Application and built it. The data migrations produced an empty database. I'm now attempting to set up a way to login as there is no account setup on the login page. The use of the AbstractUser is supposed to require that an email is required in place of a user name.
Trying to find a way to set up the login.
The User model is:
class User(AbstractUser):
email = None
first_name = None
last_name = None
REQUIRED_FIELDS = []
def __str__(self):
return self.email
class Meta:
db_table = 'User'
Table Description is:
Table "public.User"
Column | Type | Collation | Nullable | Default
--------------+--------------------------+-----------+----------+------------------------------------
id | integer | | not null | nextval('"User_id_seq"'::regclass)
password | character varying(128) | | not null |
last_login | timestamp with time zone | | |
is_superuser | boolean | | not null |
username | character varying(150) | | not null |
is_staff | boolean | | not null |
is_active | boolean | | not null |
date_joined | timestamp with time zone | | not null |
Using this description I've attempted to some add data to facilitate being able to log in.
select * from "User";
id | password | last_login | is_superuser | username | is_staff | is_active | date_joined
----+--------------+------------+--------------+----------+----------+-----------+------------------------
1 | blankDon012! | | t | donfox1 | t | t | 2021-11-12 00:00:00-05
Not able to insert an email address. Articles on internet seem to not quite address this issue so far.
I'm new to django. I've been coding with sql but django orm is hard for me to convert my knowledge of sql to orm models.
I've client model
class client(models.Model):
c_id = models.AutoField(primary_key=True)
name= models.TextField()
age=models.IntegerField()
and address model
class address(models.Model):
c_id = models.ForeignKey(client, on_delete=models.CASCADE)
addr = models.CharField(max_lenght=20)
city= models.CharField(max_lenght=20)
This is my table
---------------------------
| c_id|Name | age |
---------------------------
| 1 | John | 23 |
----------------------------
| 2 | Rose | 20 |
----------------------------
------------------------------
| c_id|addr | city |
------------------------------
| 1 | buspark | florida|
------------------------------
| 2 | homesquare| florida|
------------------------------
how to get allclient with address in list
Look at values() docs
The values() method takes optional positional arguments, *fields,
which specify field names to which the SELECT should be limited. If
you specify the fields, each dictionary will contain only the field
keys/values for the fields you specify. If you don’t specify the
fields, each dictionary will contain a key and value for every field
in the database table.
__ allows get related data, so in your case it could look like this
address.objects.values('c_id__c_id', 'c_id__name', 'c_id__age', 'addr', 'city')
If we consider the three following models: clients, companies, contacts.
Clients can purchase goods from several companies and a company has many clients. Moreover, a company has several "contact" types (email, fax, phone,...).
class Clients(models.Model):
fname= models.CharField(max_length=45, null=False)
company= models.ManyToManyField(to='Companies', related_name='provider', blank=True)
class Companies(models.Model):
name= models.CharField(max_length=45, null=False)
class Contacts(models.Model):
contact= models.CharField(max_length=45)
type= models.IntegerField(choices=TYPE)
company= models.ForeignKey(to='Companies', related_name= 'company_contacts', on_delete=models.CASCADE)
For a given client, I would like to retrieve all the companies he purchased from along with all the company's details (stored in the model "Contacts"). In SQL, with an intermediate table (clients_companies), I will do:
SELECT cl.fname, cp.name, ct.contact, ct.type
FROM Clients cl
JOIN Clients_Companies cc ON cl.id = cc.clients_id
JOIN Companies cp ON cp.id = cc.companies_id
JOIN Contacts ct ON cp.id = ct.companies_id;
Which will give:
+---------+-----------+-----------------+--------+
| fname | name | contact | type |
+---------+-----------+-----------------+--------+
| Client1 | Company A | 333-555-1234 | phone |
| Client1 | Company A | email#email.com | email |
| Client1 | Company B | 202-555-0191 | phone |
| Client1 | Company B | 202-555-9999 | fax |
| Client1 | Company B | arg#arg.com | email |
+---------+-----------+-----------------+--------+
In django, I'd like something similar to:
data = [
{'Company A':[{'type':'phone', 'contact':'333-555-1234'},
{'type':'email', 'contact':'email#email.com'}],
'Company B':[{'type':'phone', 'contact':'202-555-0191'},
{'type':'fax', 'contact':'202-555-9999'},
{'type':'email', 'contact':'arg#arg.com'},],
}]
Any suggestion to solve this is welcome. Also, if you have sources to learn querying data using django ORM I will be really happy as I found really difficult to work the django way when coming from SQL.
I use intermediate model for "ManyToManyField using the through"
Normally,If I don't use intermediate field, the m2m relation will be unique and can't have the duplicated data.
After I use intermediate model. the relation between m2m can have same data. like this
| | ['0'] (
| | | addToProfile => Array (0)
| | | (
| | | )
| | | endDate = NULL
| | | feedType = "N"
| | | id = 1
| | | info = "Big Kuy No Fear"
| | | likeMaker => Array (3)
| | | (
| | | | ['0'] = "/api/v2/user/2/"
| | | | ['1'] = "/api/v2/user/2/"
| | | | ['2'] = "/api/v2/user/2/"
| | | )
| | | like_count = "3"
I am building a social network. So this is my feed object that has 3 like_counts . But the three of this like come from the same user "/api/v2/user/2/"
I try to add "unique=True" attribute at m2m field but django come up with the error because It doesn't grant the permission to add the "unique" attribute to m2m field at first. Can anyone help me?
Try to use unique_together in your intermediate model.
class M2MModel(models.Model):
field1 = models.ForeignKey(Model1)
field2 = models.ForeignKey(Model2)
class Meta:
unique_together = ('field1', 'field2')
unique_together doesn't work for M2M relationships. More info.
I just finished a feature that quite similar with your requirement but my choice is to use another simple model as an intermediate model.
Here is my code.
class Vote(models.Model):
class Meta:
unique_together = ['content', 'by']
content = models.ForeignKey(Content)
by = models.ForeignKey(User)
In my case I don't see any benefit to implement ManyToManyField.
Update:
I just found from here that Django is not going to make any built-in unique together for ManyToManyField. You have to implement your own validation to make it unique.