django Getting unwatched items - python

class Photo(models.Model):
...
viewsT = models.ManyToManyField('PhotoViewT', symmetrical=False)
...
class PhotoViewT(models.Model):
user = models.ForeignKey(User)
creationdate = models.DateTimeField()
I store photos' information in "Photo" table and information about views in "PhotoViewT" table (Here is "user" who watched photo and "creationdate" when he watched it). On "photo" I have m2m field to views, where I add information about all views.
My task is to get photos, those haven't been already watched by current defined user. I have no clue how to craft this query.
Something like
Photo.objects.filter(viewsT__user__doesnt_contain=targetUser)
Expression above hardly does work. Any solutions? Thank you in advance!

Ref the doc. Try
Photo.objects.exclude(viewsT__user=targetUser)

Photo.photoviewtset.all() will fetch you all PhotoViewT instances associated with that Photo.
Photo.photoviewtset.filter(user=<your_current_user) will fetch you all PhotoViewT instances associated with that Photo filtered by your current_user.
Note: You do not need the ManyToManyField in the Photo model for this

Photo.objects.exclude(viewsT__in=PhotoViewT.objects.filter(user=request.user))
OR
Photo.objects.filter(~Q(viewsT__in=PhotoViewT.objects.filter(user=request.user)))

Related

how to get a column value of foreign key in the form of object?

There is 2 models Registration and RegistrationCompletedByUser, I want Registration queryset from RegistrationCompletedByUser with filters(user=request.user, registration__in=some_value, is_completed=True) over RegistrationCompletedByUser. Hence result should be like <QuerySet [<Registration: No name>, <Registration: p2>, <Registration: p-1>]>.
Now what I tried is
Registration.objects.prefetch_related('registrationcompletedbyuser_set') but filters() not working. Another way I tried is model Managers but don't pass parameters for custom filtering.
models.py
class Registration(models.Model):
name=models.CharField(max_length=255)
number=models.SmallIntegerField(null=True, blank=True)
class RegistrationCompletedByUser(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
registration= models.ForeignKey(Registration, on_delete=models.CASCADE)
points = models.SmallIntegerField(default=100)
is_completed = models.BooleanField(default=False)
If I understood this properly, you want to get all Registrations that related to a query instead of a single object.
qs_1 = RegistrationCompletedByUser.objects.filter(user=request.user, is_completed=True).values_list("registration__id", flat=True)
qs_2 = Registration.objects.filter(id__in=qs_1)
As I understood your question is related to django. So actually there is common way to get related query set from another. When you specify ForeignKey to another model actually django automatically creates 'Related Model' + '_set' relation.
I actually didn't get from you question what you are intended to do. In your situation there are many RegistrationCompletedByUser related to one Registration. So what you can do it's to receive all RegistrationCompletedByUser instances from Registration instance by related name for ForeignKey registration of RegistrationCompletedByUser which in your case registration_set. Actually better to specify in RegistrationCompletedByUser model related name as attribute like this:
models.ForeignKey(Registration, on_delete=models.CASCADE,
related_name='registrations')
And after this let's say you have instance of Registration reg1. So to receive queryset of RegistrationCompletedByUser:
reg1.registrations.all()
And you can use filter on it with attributes from Registration model.
And if you want to receive Registration from RegistrationCompletedByUser, again in your case it's just one Registration to many RegistrationCompletedByUser, so let's say we have reg_completed_1, to receive it's only one registration:
reg = reg_completed_1.registration

Set ManyToManyField with particular users from another model's ManyToMany Field

I am building a simple class group app in which I am trying to add particular users from another model's ManyToFieldField to a new model's ManyToFieldField.
class ClassGroup(models.Model):
admins = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='admins')
members = models.ManyToManyField(settings.AITH_USER_MODEL)
title = models.CharField(max_length=9999, default='')
class ClassGroupInvite(models.Model):
class_group = models.ForeignKey(ClassGroup, on_delete=models.CASCADE)
invite_receiver = models.ManyToManyField(class_group.admins.all())
invite_sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
As you can see that I am filtering (send request only to class group admins) in ClassGroupInvite with setting ManyToManyField with ClassGroup.admins
But when I try this then it is showing
ManyToManyField(<django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x000001CE78793280>) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string 'self'
I also read the documentation about it, But I didn't find anything about defining it.
then I tried using ClassGroup.admins.all then it showed
AttributeError: 'ManyToManyDescriptor' object has no attribute 'all'
I have tried many times but it is still not working, Any help would be much Appreciated. Thank You in Advance.

showing which post a user liked/saved with python django.

I have trouble to display the ''saved''/''liked'' posts of my users in django/admin. I would like to have a field in the Adminpage to show which user likes which posts. I made an Userprofile model where all extra information (besides the one on the given django admin user Profile) are stored. so here is my model View:
class UserProfile(models.Model):
user = models.OneToOneField(User, null=True)
#likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True,default=1, related_name='likes')
likedPosts=models.ManyToManyField('self')
Field1 = models.CharField(max_length=50,default='Sunny')
Field2 = models.CharField(max_length=50,default='')
class Meta:
ordering =['-user']
#def __unicode__(self):
# return self.user.username
User.profile =property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
right now in the liked post field I have only some usernames or "User object"
I tried all kinds of combinations to get the information into the admin page but as you can see I did not make it.
I tried to change the unicode and of course the liked post line. If you need more information please tell me so. I appreciate every kind of help.
django admin isn't really meant to support many to many relationships from both directions in the django admin. However, the link below contains a workaround that I think should address your problem with a better explanation of why many-to-many relationships are only shown from one side by default.
(many-to-many in list display django).
so for everybody who wants to do something similar this worked for me:
class UserProfile(models.Model):
likedPosts = models.ManyToManyField('self',default=None,blank=True)
def __unicode__(self):
return "{0}".format(self.user.likes.all())

Retrieving a ForeignKey attribute based on the URL of the website?

I am trying to create a function that allows individuals to post something on an associated userpage. I have created both the model ‘newpost’ and ‘newpostform’ (below). I am having trouble writing the view function to look at the current URL of the page and then take that parameter and attach it to the newpost model’s ForeignKey field automatically. For example, if I am at the URL myapp.com/userpage1 and I click on the “post” button on that page, I want to create a newpost object which automatically has the ForeignKey field filled in as ‘userpage1’. Basically, I am trying to create an app where people can easily navigate userpages by entering the userpage parameter into the URL and easily make posts on those pages quickly and concisely - kind of like how reddit's subreddit system works by entering the name of the subreddit into the URL bar. Thanks for any help and hints.
model:
class newpost(models.Model):
newlinktag = models.ForeignKey(‘userpage’) #tags link to which userpage the post belongs to
postcontent = models.CharField(max_length=1024)
postdate = models.DateTimeField(auto_now_add=True) #submission timestamp.
postlikes = models.IntegerField(null=False, default=0)
def __unicode__(self):
return self.postcontent
form:
class newpostform(forms.ModelForm):
postcontentform = models.CharField(max_length=1024)
class Meta:
model = newpost
urls.py:
url(r'^(?P<url_user_id>[\w\-]+)/$', your_view)
views.py
def your_view(request, url_user_id)
# you have the foreign key in the url_user_id field.
...
if request.POST:
new_post_with_foreign_key = newpost(newlinktag=url_user_id, ...)
...
new_post_with_foreign_key.save()
Don't do this in the form. Exclude the FK field from the modelform altogether, and set it in the view on save.
if form.is_valid():
post = form.save(commit=False)
post.newlinktag = page
post.save()
(You might like to consider following PEP8 and using some CapitalLetters in your class names, and underscore_names in your field names. It'll make your code much easier to read.)

Django Adding a ManyToManyField to ModelForm

Sorry that this is like the thousandth question for this issue but I still can't see a light at the end of the tunnel.
Lets say I have two models:
class Video(models.Model):
title = models.CharField(u"Titel",max_length=200)
slug = AutoSlugField(populate_from='title',unique=True)
date = models.DateField("Datum")
description = models.TextField(u"Beschreibung")
user = models.OneToOneField(User, blank=True, null=True)
class Channel(models.Model):
name = models.CharField(u"Name",max_length=30)
slug = AutoSlugField(populate_from='name',unique=True)
videos = models.ManyToManyField('videoportal.Video',related_name="contained_videos",blank=True,null=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
As you see I want to have a channel with video(s) in it. So if I ad a video using a ModelForm like this
class VideoForm(ModelForm):
class Meta:
model = Video
the form I get will not contain a input field to select a channel (of course not). So how can I do this? How can I have a input field in my form to select one channel with a drop down?
Thanks,
Philip
If a video only belongs in one channel just give your Video model a ForeignKey to your Channel model. If it should belong to more than one channel I'd use a ManyToManyField in the Video model, as already suggested.
I think this would fit the idea of uploading videos and adding it to a channel far better than doing it the other way around.
Try putting the ManyToMany field in the Video model and omit it from the Channel model:
class Video(model.Model):
...
channels = model.ManyToManyField('videoportal.Channel', related_name='videos')
...
If you want a simple dropdown to select a single channel, why is it a many-to-many realationship between videos and channels?
Use a custom form instead of Django ModelForm.
probably something like this,
class VideoForm(forms.Form):
title = forms.CharField()
description = forms.TextField()
channel = forms.ModelChoiceField(queryset= Channel.objects.all(), empty_label=None)
do your validation in a view. Use Model save() method to save information contained in your POSTed form.

Categories