Looping through model objects to check whether a field is populated - python

I am working on a django project and am trying to figure out how to loop through all of my "task" model objects and check whether the ManyToMany "user" field is populated by user model objects of a certain type or not.
Is there a simple way to iterate over all of the model objects to do this?

You don't have to iterate objects. For example, assume that you have a Task model similar to:
class Task(models.Model):
users = models.ManyToManyField(User)
...
then the following query will return all the Task objects which has at least one related user who is a "Student":
Task.objects.filter(users__type='Student')
The double underscore (__) tells Django to traverse the many-to-many relation and fetch the type column from the User table.

Related

Django user customization database tables

I am trying to build a Django website where the user is able to create custom objects known as items. Each item needs to be able to have certain properties that are stored in the database. For example an item would need properties such as
Serial Number,
Description,
Manufacture Date
However I want the user to be able to specify these fields similar to what Microsoft dynamics allows . For example a user should be able to specify they want a text field with the name Model Number, associated with a specific item type and from then on they can store those properties in the database.
I am not sure the best approach to do this because a standard database model, you already have all the fields defined for a specific table, however this essentially means i have to find a way to have user defined tables.
Does anyone know a good approach to handle this problem, at the end of the day I want to store items with custom properties as defined by the user in a database.
thanks
There are multiple ways you can go.
In non-relational databases you don't need to define all the fields for a collections ( analogous to a table of RDBMS).
But if you want to use SQL with Django, then you can define a Property Model.
class Property(models.Model):
name = CharField()
value = CharField()
item = models.ForeignKey(Item, on_delete=models.CASCADE)
class Item(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
You can render a FormSet of Property form. To add extra empty forms on the fly, render dynamic formsets.

In Django how can I filter objects in a QuerySet based on a many to many relationship?

So I have a user Profile model with a data attribute which is a many to many field representing a Profile "friending" another Profile like on Facebook. Here's the code for that:
friends = models.ManyToManyField("self")
What kind of query can I do to write a method that gets me all the Profiles that are friends with a current Profile?
friends = Profile.objects.filter(friends=self.pk)
This seems to give an empty QuerySet when I test it.
Solved it:
For Django Querysets you use the double underscore __ to separate the attribute with other fields you want to check so in this case we're filtering the friends attribute where the pk is this Profile's pk.
friends = Profile.objects.filter(friends__pk=self.pk)
return friends

how to store a dictionary in django model as a field?

I'm trying to build up a social network and want my users to have 3 privacy options [privtae, public, friends_except],
private and public are boolean fields and friends_except is a list of users
if it's not possible to store a dict in a model as a field then what do I do to implement want I want to.
Firstly, if you're using a relational database, you can either create a new model containing all those attributes, and link them as foreign key with main model, or denormalize it to store all the fiels separately in the base model iteself. If you're using a nosql system like MongoDB, then you can certainly store it as a dictionary or JSON field.
Secondly, since at a time user can have only one privacy option selected, why to have a separate model or even a dictionary type construct. Just store it as a CharField with choices specified.
PRIVACY_CHOICES = [('public', 'public'), ('private', 'private', ('custom', 'custom')]
privacy_choice = models.CharField(max_length=256, choices=PRIVACY_CHOICES)
friends_allowed = models.ManyToManyField('User', blank=True)
look, instead of your approach what I would recommend you is to create a model let's say Friends_except with 1 field as a Foreign key to your user model. you'll be able to send all of the users you wanna block to your blocked user table
(that's kinda what happens on facebook)
then in the view, you can easily make a simple query
if:
user.is_authentictaed and is not in users.friends_except.objects.all()
" display your post" else Nah.

Pass model objects to choices field in django

I have a model called Student that has a manytomany relationship with a model called Courses. I have another model called Attend in which I want to get all the courses the student is taking and pass it in as a select menu containing the courses the student is taking. I tried to get the id using the foreign key "student" and then get courses belonging to that student and put it in a list and pass it to choices but it didn't work obviously. I would like to know how I can get the courses belonging to the student to appear in the select menu.
Here is my model.
class Attend(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE, default="")
time_signed_in = models.DateTimeField(auto_now_add=True)
isSignedIn = models.BooleanField(default=False)
# Below does not work, I get an error 'ForeignKey' object has no attribute 'id'
#courses = User.objects.get(id=student.id).courses
course = models.ForeignKey(Course, on_delete=models.CASCADE)
To render the courses the student is taking you should try using django forms.
If I understand correctly, you want a form that uses ModelMultipleChoiceField:
Allows the selection of one or more model objects, suitable for
representing a many-to-many relation.
class AttendForm(forms.Form):
courses = forms.ModelMultipleChoiceField(queryset=Courses.objects.filter(student__id=id))
That exapmple would only work to show the data to the user and then retrieving its choice. There is a slightly different approach to this case and that is using a ModelForm.
Every ModelForm also has a save() method. This method creates and saves a database object from the data bound to the form.
ModelForm is a "database driven" form in which you can perform many task involving calls to the database easily.
Note: The queryset I used in the example is just an example, you dont have to use it that way.

Django ORM get all many-to-many fields of an instance

I have a model Project, which has m2m relationship with Category, Specialty, Competitor.
I have an instance of this model Project. I can get all the fields of the model using
Fields of model
object._meta.fields
This gives me the all the fields in the model; I just iterate over these can check if something is updated by the user or not.
I also want to know what ManyToMany relations this object has rather than Statically calling all project.category_set.all()
I want to know, if there is any way that i can get a list of all these relation and iterate over them and get they values of these?
AIM
Check if the data in ManyToMany relations have updated by the user or not specific to this instance.
Code
def save(self, request, instance):
project = super(RequestForm, self).save(commit=False)
project.competitor.all() # Gives the list which is in data base (not new list form the form values.
project.save()
project.instance.save_m2m()
project.competitor.all() # Gives the list which is in data base (With the changing have been made.
How to check if the Competitor data has been updated.

Categories