I want to write Query Set that show every User Own IPs and Asset_Names
from django.db import models
from django.contrib.auth.models import User
class Asset(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
IP = models.GenericIPAddressField()
Asset_name = models.CharField(max_length=255)
I want every user see details(IP,Asset_Name) in own user Profile
The problem comes when trying to query the database, and using a string compared to an auth.User object. I do not know how to get around this?
If you want to filter Asset based on the username you can do something like the following:
Asset.objects.filter(user__username='something')
Related
I want to get all users information to set up user profiles including superuser, but somehow my code doesn't get superuser data . Please have a look
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
as per the docs, Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model(). This method will return the currently active user model – the custom user model if one is specified, or User otherwise. So use User = get_user_model() or settings.AUTH_USER_MODEL if you a custom user
I'm new to django. What I'm trying to achieve is when the ProductType combobox is changed, the fields changes to its specific fields then the users inputs using those field and entered to the database. My problem is how to create a flexible model that would accept extra fields
from django.db import models
class Product(models.Model):
"""SKU"""
stock = models.IntegerField(default=None)
class ProductType(models.Model):
product_field = models.ForeignKey(ProductFields, on_delete=models.CASCADE)
name = models.CharField(max_length=255)
class ProductFields(models.Model):
"""Fields of ProductType"""
Here's an DB example I'm trying to achieve See Image
SQL database is not suitable for that purpose.
Look for non-SQL databases for ex. Firebase
In Django User model, we store the last_login to know when is the users last login.
But assuming i am logging from firefox and chrome browsers and I want to store the information of the device and its login time, how can we do that.
Later i can see from where all the devices the user is currently logged in and what times is logged in from those devices.
Consider creation of a new model with relation many to one to application User.
This model named say UserSession could store information such as device type, login time etc. and could be easily queried for given user.
import datetime
from django.conf import settings
from django.db import models
from django.utils import timezone
class UserSession(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
device_type = models.CharField(max_length=255)
login_time = models.DateTimeField(default=timezone.now)
is_active = models.BooleanField(default=True)
Instance of this model could be created on each new login time.
I recently added a created_by attribute in Store model. Since this automatically gets a current logged in user when a store is created, if I don't manually assign any user, that column will be forever null.
class Store(models.Model):
...
created_by = ForeignKey(settings.AUTH_USER_MODEL, related_name='stores_of_created_by', null=True, blank=True)
So, I want to assign a user manually. I think Django Shell (something that can be triggered through python manage.py shell) would be a good way to assign users manually.
I'm very confused how I can manually assign a user in a specific attribute of all stores. So far I got a specific user and all stores in the following way.
from django.contrib.auth.models import User
from boutique.models import Store
stores = Store.objects.all()
user = User.objects.get(username='admin#gmail.com')
After that, I need to loop through all stores and assign the user in created_by of all stores. How can I do that in Django Shell?
Try this
from django.contrib.auth.models import User
from boutique.models import Store
stores = Store.objects.all()
user = User.objects.get(username='admin#gmail.com')
for store in stores:
store.created_by = user
store.save()
loop through the Store QuerySet and assign created_by attribute with specific User instance (here it is user)
If you wish to create Store objects with created_by as admin, change your model as below,
from django.contrib.auth.models import User
def default_admin():
return User.objects.get(username='admin#gmail.com')
class Store(models.Model):
created_by = ForeignKey(settings.AUTH_USER_MODEL, related_name='stores_of_created_by', default=default_admin)
If you are updating all the stores, this will be faster.
Iterating over the stores fetches the record from the db and writes the updated record, causing atleast twice as many queries as the number of records in the DB.
admin = User.objects.get(username='admin#gmail.com')
Store.objects.update(created_by=admin)
This shall update all the stores in just two queries.
In Django model I am making a table 'followers', which has:
user's id. (this is followed by)
user's id (this is follower)
that's simple a user can follow other users.
How should I define the model in Django?
I tried this, but does not work:
user = models.ForeignKey('self')
follower_id = models.ForeignKey('self')
How should this be done?
thanks
The 'self' argument won't work unless you have a model called self.
Assuming that your assignment model is called Following, and you're using the built in User model then you can do:
class Following(models.Model):
target = models.ForeignKey('User', related_name='followers')
follower = models.ForeignKey('User', related_name='targets')
This will likely need some further uniqueness and validation logic.
Note the related_name attribute, see https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ForeignKey.related_name. This means that for a given user object you can do user.targets.all() to get users they follow, and user.followers.all() to get users who follow them.
Note also that Django returns target model instances, not IDs, in the ORM. This means that even though the underlying table may be called follower_id, in the python code following.follower will return an actual User object.
Seeing as Following is actually the through table for the many-to-many relationship between Users. I would create a Profile model which extends the Django User model, and then declare the many-to-many relationship (using ManyToManyField).
from django.contrib.auth.models import User
from django.db import models
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
following = models.ManyToManyField(User, related_name='followers')
Use the many to many field.
followers = models.ManyToManyField('self', symmetrical=False)