Model Mommy Recipe with Reverse FK - django

I'm using model_mommy with Django tests to create objects. I'm having trouble creating a model with a reverse FK. I can do it the opposite way round as a workaround, but whilst it works it doesn't look right so I wonder if I can do it the other way round?
Say I have two models, User and Profile, related via an FK from Profile to User (it's not a one to one, it's just an FK). The Profile model has a bool attribute call is_aardvark.
In model mommy I can create recipes like so:
aardvark_profile = Recipe(Profile, is_aardvark=True)
non_aardvark_profile = Recipe(Profile, is_aardvark=False)
Then I can create a User with an aardvark profile in my test with something like:
user = mommy.create_recipe(aardvark_profile).user
This doesn't seem right, as I'm creating a user via the aardvark_profile recipe. I want to create a User via some sort of User recipe ideally (maybe in future I'll have some other model FKd to User, so the above wouldn't work).
I've tried things like the below, which doesn't work:
# doesn't work
broken_aardvark_user = Recipe(User, profile_set=mommy.create_recipe(aardvark_profile)
Is this even possible? Any ideas? I could just create a helper method to do this for me if all else fails.
Thanks!

You could do this:
from model_mommy.recipe import Recipe, related
aardvark_profile = Recipe(Profile, is_aardvark=True)
aardvark_user = Recipe(User, profile_set=related('aardvark_profile'))
Hope it helped
[1] http://model-mommy.readthedocs.org/en/latest/recipes.html#recipes-with-foreign-keys

Related

User model with static set of related models

Say I have a User model in django and I want to add some achievements to users. So I've created an Achieve model:
class Achive:
type = ....
value = ....
status = BooleanField(default=False)
I want all those achieves be a static set of models for every user (20 instances, for example) with ability to delete old and create new achieves. The problem is how to do it. Expected flow is:
1) user granted to use achievement system;
2) user got all those achieves (in admin panel shows like a table);
3) in admin panel per user I can change status of every achieve (affects only on edited user);
4) if new Achieve instance is created — add to all users who have achievements;
5) if existed Achieve instance has been deleted — remove from all users;
Solutions with I came up:
1) use Achieve model with jsonfield. store achieves in json like dictionary, use custom widget for admin panel to show checkboxes to change status). But where to store global set of achievements to create new/delete old ones? how to manage it?
2) use many to many field to Achieve and Achieve model without status. Why: if relation between User ← → Achieve exists, that means that user earn an achieve.
Both solutions I don't really like so hope for your advice.
P.S. sqlite is used as db and not allowed to use another (like mongo, etc.)
Thanks in advance!
What you want is a ManyToMany relationship between Achieve and User, but with the ability to store extra data on the relationship (the status for example).
With a normal ManyToManyField on a Model, Django actually creates an intermediate model to store the relationships in the database. By adding a through argument to your ManyToManyField, you can specify the intermediate model used for the relationship and store extra data with the relationship, as documented here:
class Goal(models.Model):
type = ...
value = ...
achievers = models.ManyToManyField(to=User, through='Achievement', related_name='goals')
class Achievement(models.Model):
status = models.BooleanField()
date_reached = models.DateField(null=True)
goal = models.ForeignKey(to=Goal, on_delete=models.CASCADE)
achiever = models.ForeignKey(to=User, on_delete=models.CASCADE)
then you can create and query the relationships like this, assuming you have a user and a goal:
achievement = Achievement.objects.create(status=True, date_reached=date(2018, 10, 12), achiever=user, goal=goal)
user.goals.filter(achievement__status=True) # gives the achieved goals of a user
goal.achievers.filter(achievement__status=True) # gives the users that achieved a goal

django how to assign a User foreign key id within view

I am trying to create a model with a foreign key which references the django model User.
I have found that you are supposed to use this model when creating something like this:
author = models.ForeignKey(User)
however any time i try to assign this from my view with this line:
if form.is_valid():
c = form.save(commit=False)
c.author=request.user.id
c.save()
I get an error complaining about how author should come from the model User. There is no User property (at least that i (a noob working on their first django project) could find) which has the user id. what is the preferred method for linking a post to it's author in django? am i going about this completely the wrong way? is there a better way of solving this problem that i am just not thinking of?
You just assign this only not id,
c.author=request.user
For assigning user, it should be like:
c.author= User.objects.filter(id= request.user.id)[0]

Django making sure user and user profile have same pk

Right now I'm using Django's built in admin system to manage users, to which I've attached a profile to contain additional data using the following:
class Profile(models.Model):
user = models.OneToOneField(User, editable = False)
# Data fields here...
As it stands the User and Profile pk (and accordingly id number) will be the same if and only if the profile is created right after the user is created. I could guarantee that this would be the case during the registration process, and while that would cover most uses, creating users with the admin interface could cause mismatched ids to occur. Thus this does not seem like a very robust way to solve this problem and I'd like to hardcode the pk's to be the same. I'm not sure how to do this.
I thought the following would work:
profile_id = models.IntegerField(default=user.pk, editable = False,
primary_key = True)
But it gives me the error:
AttributeError: 'OneToOneField' has no attribute 'pk'
What's the best way to guarantee that the profile and user have the same pk? Note: I'd really rather not deal with extending the base user model as using the OneToOneField to link the two seems to be sufficient for all my needs.
Thanks!
[edit]
My reasoning for asking the question:
My immediate problem was that I wanted a dictionary of values of the User's Profile, which I was retrieving usingprofile_values = Profile.objects.filter(pk=user.id).values()[0]. This highlighted the bug, and I "hacked" around it last night using pk=user.profile.id instead. In the light of the morning this does not seem like such a terrible hack. However, it seems like having pk discrepancies could lead to quiet and hard to catch bugs down the line, and thus forcing them to match up would be a Good Idea. But I'm new to Django so I'd entirely accept that it is, in fact, never a problem if you're writing your code correctly. That said, for almost academic reasons, I'd be curious to see how this might be solved.
[/edit]
Like you already agree that it was never a problem because we have a OneToOne mapping between the two models.
So when you need to get the profile obj corresponding to a User:
profile_values = Profile.objects.get(user_id=user)
assuming,
class Profile(models.Model):
user = models.OneToOneField(User)
...
If your column name is not user, then use the corresponding name in get query.
Still if you are curious as to how to achieve same pk for both models, then we can set a signal on every save of User model. See the documentation.
def create_profile(sender, **kwargs):
if kwargs["created"]:
p = Profile(user=kwargs["instance"], ...)
p.save()
django.db.models.signals.post_save.connect(create_profile, sender=User)
create_profile() will be called every time any User object is saved.
In this function, we create Profile object only if a new User instance has been created.
If we start from blank slate, then I think this will always make sure that a Profile exists for every User and is created right after User was created; which in turn will give same pk for both models.
pk is a parameter in a filter() query, but not a field name. You probably want to use user.id.

Using a Django Custom Manager

Can anyone help me create a custom manager that does the following....
This is just a learning exercise for me, it's not a real application so I'm after as much explanation as possible.
1) takes 2 objects, its self (Person) and Profile
2) divides person.age with profile.dog_years
3) adds this to model
My guess is that first I create a custom manager in my models.py
class PersonManager(models.Manager):
def make_score(self,profile):
Within the custom manager I then do the math self.age / profile.dog_years.
Then some how return it?
Add it to the model i.e. dogAge = PersonManager()
Outcome:
Then what I'm hoping to happen is that when I get all persons in my view
return Profile.objects.filter() (somehow pass profile here?) it has a new field called dogAge with the dog ages for all persons listed.
This isn't something that you'd do in a Manager. This is a job for a normal Model method.
Manager methods are for things that modify the query in some way. That's not what you want to do: you want to annotate a property to each object in the queryset. Since that doesn't require any further database calculations, a model method is the appropriate place.

Django - Customizeable UserProfile

So I've got a UserProfile in Django that has certain fields that are required by the entire project - birthday, residence, etc. - and it also contains a lot of information that doesn't actually have any importance as far as logic goes - hometown, about me, etc. I'm trying to make my project a bit more flexible and applicable to more situations than my own, and I'd like to make it so that administrators of a project instance can add any fields they like to a UserProfile without having to directly modify the model. That is, I'd like an administrator of a new instance to be able to create new attributes of a user on the fly based on their specific needs. Due to the nature of the ORM, is this possible?
Well a simple solution is to create a new model called UserAttribute that has a key and a value, and link it to the UserProfile. Then you can use it as an inline in the django-admin. This would allow you to add as many new attributes to a UserProfile as you like, all through the admin:
models.py
class UserAttribute(models.Model):
key = models.CharField(max_length=100, help_text="i.e. Age, Name etc")
value = models.TextField(max_length=1000)
profile = models.ForeignKey(UserProfile)
admin.py
class UserAttributeInline(admin.StackedInline):
model = UserAttribute
class UserProfile(admin.ModelAdmin):
inlines = [UserAttibuteInline,]
This would allow an administrator to add a long list of attributes. The limitations are that you cant's do any validation on the input(outside of making sure that it's valid text), you are also limited to attributes that can be described in plain english (i.e. you won't be able to perform much login on them) and you won't really be able to compare attributes between UserProfiles (without a lot of Database hits anyway)
You can store additional data in serialized state. This can save you some DB hits and simplify your database structure a bit. May be the best option if you plan to use the data just for display purposes.
Example implementation (not tested)::
import yaml
from django.db import models
class UserProfile(models.Model):
user = models.OneToOneField('auth.User', related_name='profile')
_additional_info = models.TextField(default="", blank=True)
#property
def additional_info(self):
return yaml.load(self._additional_info)
#additional_info.setter
def additional_info(self, user_info_dict):
self._additional_info = yaml.dump(user_info_dict)
When you assign to profile.additional_info, say, a dictionary, it gets serialized and stored in _additional_info instead (don't forget to save the instance later). And then, when you access additional_info, you get that python dictionary.
I guess, you can also write a custom field to deal with this.
UPDATE (based on your comment):
So it appears that the actual problem here is how to automatically create and validate forms for user profiles. (It remains regardless on whether you go with serialized options or complex data structure.)
And since you can create dynamic forms without much trouble[1], then the main question is how to validate them.
Thinking about it... Administrator will have to specify validators (or field type) for each custom field anyway, right? So you'll need some kind of a configuration option—say,
CUSTOM_PROFILE_FIELDS = (
{
'name': 'user_ip',
'validators': ['django.core.validators.validate_ipv4_address'],
},
)
And then, when you're initializing the form, you define fields with their validators according to this setting.
[1] See also this post by Jacob Kaplan-Moss on dynamic form generation. It doesn't deal with validation, though.